netstat: Initial implementation.
[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 editbox
22  */
23
24 #include <stdlib.h>
25 #include <string.h>
26
27 #define COBJMACROS
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
30
31 #include "wine/debug.h"
32 #include "undocshell.h"
33 #include "pidl.h"
34 #include "shell32_main.h"
35 #include "shellapi.h"
36 #include "shresdef.h"
37 #include "shellfolder.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_GetImageLists(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             ILFree(pidlChild);
232             ILFree(pidlParent);
233             return;
234         }
235         hr = IShellFolder_BindToObject(lpsfDesktop, pidlParent, 0, &IID_IShellFolder, (LPVOID*)&lpsfParent);
236         IShellFolder_Release(lpsfDesktop);
237     }
238
239     if (FAILED(hr)) {
240         WARN("Could not bind to parent shell folder! hr = %08x\n", hr);
241         ILFree(pidlChild);
242         ILFree(pidlParent);
243         return;
244     }
245
246     if (!_ILIsEmpty(pidlChild)) {
247         hr = IShellFolder_BindToObject(lpsfParent, pidlChild, 0, &IID_IShellFolder, (LPVOID*)&lpsfRoot);
248     } else {
249         lpsfRoot = lpsfParent;
250         hr = IShellFolder_AddRef(lpsfParent);
251     }
252
253     if (FAILED(hr)) {
254         WARN("Could not bind to root shell folder! hr = %08x\n", hr);
255         IShellFolder_Release(lpsfParent);
256         ILFree(pidlChild);
257         ILFree(pidlParent);
258         return;
259     }
260
261     flags = BrowseFlagsToSHCONTF( info->lpBrowseInfo->ulFlags );
262     hr = IShellFolder_EnumObjects( lpsfRoot, info->hWnd, flags, &pEnumChildren );
263     if (FAILED(hr)) {
264         WARN("Could not get child iterator! hr = %08x\n", hr);
265         IShellFolder_Release(lpsfParent);
266         IShellFolder_Release(lpsfRoot);
267         ILFree(pidlChild);
268         ILFree(pidlParent);
269         return;
270     }
271
272     SendMessageW( info->hwndTreeView, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT );
273     item = InsertTreeViewItem( info, lpsfParent, pidlChild,
274                                pidlParent, pEnumChildren, TVI_ROOT );
275     SendMessageW( info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item );
276
277     ILFree(pidlChild);
278     ILFree(pidlParent);
279     IShellFolder_Release(lpsfRoot);
280     IShellFolder_Release(lpsfParent);
281 }
282
283 static int GetIcon(LPCITEMIDLIST lpi, UINT uFlags)
284 {
285     SHFILEINFOW sfi;
286     SHGetFileInfoW((LPCWSTR)lpi, 0 ,&sfi, sizeof(SHFILEINFOW), uFlags);
287     return sfi.iIcon;
288 }
289
290 static void GetNormalAndSelectedIcons(LPITEMIDLIST lpifq, LPTVITEMW lpTV_ITEM)
291 {
292     LPITEMIDLIST pidlDesktop = NULL;
293     DWORD flags;
294
295     TRACE("%p %p\n",lpifq, lpTV_ITEM);
296
297     if (!lpifq)
298     {
299         pidlDesktop = _ILCreateDesktop();
300         lpifq = pidlDesktop;
301     }
302
303     flags = SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON;
304     lpTV_ITEM->iImage = GetIcon( lpifq, flags );
305
306     flags = SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_OPENICON;
307     lpTV_ITEM->iSelectedImage = GetIcon( lpifq, flags );
308
309     if (pidlDesktop)
310         ILFree( pidlDesktop );
311 }
312
313 /******************************************************************************
314  * GetName [Internal]
315  *
316  * Query a shell folder for the display name of one of it's children
317  *
318  * PARAMS
319  *  lpsf           [I] IShellFolder interface of the folder to be queried.
320  *  lpi            [I] ITEMIDLIST of the child, relative to parent
321  *  dwFlags        [I] as in IShellFolder::GetDisplayNameOf
322  *  lpFriendlyName [O] The desired display name in unicode
323  *
324  * RETURNS
325  *  Success: TRUE
326  *  Failure: FALSE
327  */
328 static BOOL GetName(LPSHELLFOLDER lpsf, LPCITEMIDLIST lpi, DWORD dwFlags, LPWSTR lpFriendlyName)
329 {
330         BOOL   bSuccess=TRUE;
331         STRRET str;
332
333         TRACE("%p %p %x %p\n", lpsf, lpi, dwFlags, lpFriendlyName);
334         if (SUCCEEDED(IShellFolder_GetDisplayNameOf(lpsf, lpi, dwFlags, &str)))
335           bSuccess = StrRetToStrNW(lpFriendlyName, MAX_PATH, &str, lpi);
336         else
337           bSuccess = FALSE;
338
339         TRACE("-- %s\n", debugstr_w(lpFriendlyName));
340         return bSuccess;
341 }
342
343 /******************************************************************************
344  * InsertTreeViewItem [Internal]
345  *
346  * PARAMS
347  *  info       [I] data for the dialog
348  *  lpsf       [I] IShellFolder interface of the item's parent shell folder 
349  *  pidl       [I] ITEMIDLIST of the child to insert, relative to parent
350  *  pidlParent [I] ITEMIDLIST of the parent shell folder
351  *  pEnumIL    [I] Iterator for the children of the item to be inserted
352  *  hParent    [I] The treeview-item that represents the parent shell folder
353  *
354  * RETURNS
355  *  Success: Handle to the created and inserted treeview-item
356  *  Failure: NULL
357  */
358 static HTREEITEM InsertTreeViewItem( browse_info *info, IShellFolder * lpsf,
359     LPCITEMIDLIST pidl, LPCITEMIDLIST pidlParent, IEnumIDList* pEnumIL,
360     HTREEITEM hParent)
361 {
362         TVITEMW         tvi;
363         TVINSERTSTRUCTW tvins;
364         WCHAR           szBuff[MAX_PATH];
365         LPTV_ITEMDATA   lptvid=0;
366
367         tvi.mask  = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
368
369         tvi.cChildren= pEnumIL ? 1 : 0;
370         tvi.mask |= TVIF_CHILDREN;
371
372         if (!GetName(lpsf, pidl, SHGDN_NORMAL, szBuff))
373             return NULL;
374
375         lptvid = SHAlloc( sizeof(TV_ITEMDATA) );
376         if (!lptvid)
377             return NULL;
378
379         tvi.pszText    = szBuff;
380         tvi.cchTextMax = MAX_PATH;
381         tvi.lParam = (LPARAM)lptvid;
382
383         IShellFolder_AddRef(lpsf);
384         lptvid->lpsfParent = lpsf;
385         lptvid->lpi     = ILClone(pidl);
386         lptvid->lpifq   = pidlParent ? ILCombine(pidlParent, pidl) : ILClone(pidl);
387         lptvid->pEnumIL = pEnumIL;
388         GetNormalAndSelectedIcons(lptvid->lpifq, &tvi);
389
390         tvins.u.item       = tvi;
391         tvins.hInsertAfter = NULL;
392         tvins.hParent      = hParent;
393
394         return TreeView_InsertItemW( info->hwndTreeView, &tvins );
395 }
396
397 /******************************************************************************
398  * FillTreeView [Internal]
399  *
400  * For each child (given by lpe) of the parent shell folder, which is given by 
401  * lpsf and whose PIDL is pidl, insert a treeview-item right under hParent
402  *
403  * PARAMS
404  *  info    [I] data for the dialog
405  *  lpsf    [I] IShellFolder interface of the parent shell folder
406  *  pidl    [I] ITEMIDLIST of the parent shell folder
407  *  hParent [I] The treeview item that represents the parent shell folder
408  *  lpe     [I] An iterator for the children of the parent shell folder
409  */
410 static void FillTreeView( browse_info *info, IShellFolder * lpsf,
411                  LPITEMIDLIST  pidl, HTREEITEM hParent, IEnumIDList* lpe)
412 {
413         LPITEMIDLIST    pidlTemp = 0;
414         ULONG           ulFetched;
415         HRESULT         hr;
416         HWND            hwnd = GetParent( info->hwndTreeView );
417
418         TRACE("%p %p %p %p\n",lpsf, pidl, hParent, lpe);
419
420         /* No IEnumIDList -> No children */
421         if (!lpe) return;
422         
423         SetCapture( hwnd );
424         SetCursor( LoadCursorA( 0, (LPSTR)IDC_WAIT ) );
425
426         while (S_OK == IEnumIDList_Next(lpe,1,&pidlTemp,&ulFetched))
427         {
428             ULONG ulAttrs = SFGAO_HASSUBFOLDER | SFGAO_FOLDER;
429             IEnumIDList* pEnumIL = NULL;
430             IShellFolder* pSFChild = NULL;
431             IShellFolder_GetAttributesOf(lpsf, 1, (LPCITEMIDLIST*)&pidlTemp, &ulAttrs);
432             if (ulAttrs & SFGAO_FOLDER)
433             {
434                 hr = IShellFolder_BindToObject(lpsf,pidlTemp,NULL,&IID_IShellFolder,(LPVOID*)&pSFChild);
435                 if (SUCCEEDED(hr))
436                 {
437                     DWORD flags = BrowseFlagsToSHCONTF(info->lpBrowseInfo->ulFlags);
438                     hr = IShellFolder_EnumObjects(pSFChild, hwnd, flags, &pEnumIL);
439                     if (hr == S_OK)
440                     {
441                         if ((IEnumIDList_Skip(pEnumIL, 1) != S_OK) ||
442                              FAILED(IEnumIDList_Reset(pEnumIL)))
443                         {
444                             IEnumIDList_Release(pEnumIL);
445                             pEnumIL = NULL;
446                         }
447                     }
448                     IShellFolder_Release(pSFChild);
449                 }
450             }
451
452             if (!InsertTreeViewItem(info, lpsf, pidlTemp, pidl, pEnumIL, hParent))
453                 goto done;
454             SHFree(pidlTemp);  /* Finally, free the pidl that the shell gave us... */
455             pidlTemp=NULL;
456         }
457
458 done:
459         ReleaseCapture();
460         SetCursor(LoadCursorW(0, (LPWSTR)IDC_ARROW));
461     SHFree(pidlTemp);
462 }
463
464 static inline BOOL PIDLIsType(LPCITEMIDLIST pidl, PIDLTYPE type)
465 {
466     LPPIDLDATA data = _ILGetDataPointer(pidl);
467     if (!data)
468         return FALSE;
469     return (data->type == type);
470 }
471
472 static void BrsFolder_CheckValidSelection( browse_info *info, LPTV_ITEMDATA lptvid )
473 {
474     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
475     LPCITEMIDLIST pidl = lptvid->lpi;
476     BOOL bEnabled = TRUE;
477     DWORD dwAttributes;
478     HRESULT r;
479
480     if ((lpBrowseInfo->ulFlags & BIF_BROWSEFORCOMPUTER) &&
481         !PIDLIsType(pidl, PT_COMP))
482         bEnabled = FALSE;
483     if (lpBrowseInfo->ulFlags & BIF_RETURNFSANCESTORS)
484     {
485         dwAttributes = SFGAO_FILESYSANCESTOR | SFGAO_FILESYSTEM;
486         r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
487                                 (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
488         if (FAILED(r) || !(dwAttributes & (SFGAO_FILESYSANCESTOR|SFGAO_FILESYSTEM)))
489             bEnabled = FALSE;
490     }
491
492     dwAttributes = SFGAO_FOLDER | SFGAO_FILESYSTEM;
493     r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
494             (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
495     if (FAILED(r) ||
496             ((dwAttributes & (SFGAO_FOLDER|SFGAO_FILESYSTEM)) != (SFGAO_FOLDER|SFGAO_FILESYSTEM)))
497     {
498         if (lpBrowseInfo->ulFlags & BIF_RETURNONLYFSDIRS)
499             bEnabled = FALSE;
500         EnableWindow(GetDlgItem(info->hWnd, IDD_MAKENEWFOLDER), FALSE);
501     }
502     else
503         EnableWindow(GetDlgItem(info->hWnd, IDD_MAKENEWFOLDER), TRUE);
504
505     SendMessageW(info->hWnd, BFFM_ENABLEOK, 0, bEnabled);
506 }
507
508 static LRESULT BrsFolder_Treeview_Delete( browse_info *info, NMTREEVIEWW *pnmtv )
509 {
510     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA)pnmtv->itemOld.lParam;
511
512     TRACE("TVN_DELETEITEMA/W %p\n", lptvid);
513
514     IShellFolder_Release(lptvid->lpsfParent);
515     if (lptvid->pEnumIL)
516         IEnumIDList_Release(lptvid->pEnumIL);
517     SHFree(lptvid->lpi);
518     SHFree(lptvid->lpifq);
519     SHFree(lptvid);
520     return 0;
521 }
522
523 static LRESULT BrsFolder_Treeview_Expand( browse_info *info, NMTREEVIEWW *pnmtv )
524 {
525     IShellFolder *lpsf2 = NULL;
526     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
527     HRESULT r;
528
529     TRACE("TVN_ITEMEXPANDINGA/W\n");
530
531     if ((pnmtv->itemNew.state & TVIS_EXPANDEDONCE))
532         return 0;
533
534     if (!_ILIsEmpty(lptvid->lpi)) {
535         r = IShellFolder_BindToObject( lptvid->lpsfParent, lptvid->lpi, 0,
536                                        &IID_IShellFolder, (void**)&lpsf2 );
537     } else {
538         lpsf2 = lptvid->lpsfParent;
539         IShellFolder_AddRef(lpsf2);
540         r = S_OK;
541     }
542
543     if (SUCCEEDED(r))
544     {
545         FillTreeView( info, lpsf2, lptvid->lpifq, pnmtv->itemNew.hItem, lptvid->pEnumIL);
546         IShellFolder_Release( lpsf2 );
547     }
548
549     /* My Computer is already sorted and trying to do a simple text
550      * sort will only mess things up */
551     if (!_ILIsMyComputer(lptvid->lpi))
552         SendMessageW( info->hwndTreeView, TVM_SORTCHILDREN,
553                       FALSE, (LPARAM)pnmtv->itemNew.hItem );
554
555     return 0;
556 }
557
558 static HRESULT BrsFolder_Treeview_Changed( browse_info *info, NMTREEVIEWW *pnmtv )
559 {
560     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
561     WCHAR name[MAX_PATH];
562
563     ILFree(info->pidlRet);
564     info->pidlRet = ILClone(lptvid->lpifq);
565
566     if (GetName(lptvid->lpsfParent, lptvid->lpi, SHGDN_NORMAL, name))
567             SetWindowTextW( GetDlgItem(info->hWnd, IDD_FOLDERTEXT), name );
568
569     browsefolder_callback( info->lpBrowseInfo, info->hWnd, BFFM_SELCHANGED,
570                            (LPARAM)info->pidlRet );
571     BrsFolder_CheckValidSelection( info, lptvid );
572     return S_OK;
573 }
574
575 static LRESULT BrsFolder_Treeview_Rename(browse_info *info, NMTVDISPINFOW *pnmtv)
576 {
577     LPTV_ITEMDATA item_data;
578     WCHAR old_path[MAX_PATH], new_path[MAX_PATH], *p;
579     NMTREEVIEWW nmtv;
580     TVITEMW item;
581
582     if(!pnmtv->item.pszText)
583         return 0;
584
585     item.mask = TVIF_HANDLE|TVIF_PARAM;
586     item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CARET, 0);
587     SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
588     item_data = (LPTV_ITEMDATA)item.lParam;
589
590     SHGetPathFromIDListW(item_data->lpifq, old_path);
591     if(!(p = strrchrW(old_path, '\\')))
592         return 0;
593     p = new_path+(p-old_path+1);
594     memcpy(new_path, old_path, (p-new_path)*sizeof(WCHAR));
595     strcpyW(p, pnmtv->item.pszText);
596
597     if(!MoveFileW(old_path, new_path))
598         return 0;
599
600     SHFree(item_data->lpifq);
601     SHFree(item_data->lpi);
602     item_data->lpifq = SHSimpleIDListFromPathW(new_path);
603     IShellFolder_ParseDisplayName(item_data->lpsfParent, NULL, NULL,
604             pnmtv->item.pszText, NULL, &item_data->lpi, NULL);
605
606     item.mask = TVIF_HANDLE|TVIF_TEXT;
607     item.pszText = pnmtv->item.pszText;
608     SendMessageW(info->hwndTreeView, TVM_SETITEMW, 0, (LPARAM)&item);
609
610     nmtv.itemNew.lParam = item.lParam;
611     BrsFolder_Treeview_Changed(info, &nmtv);
612     return 0;
613 }
614
615 static LRESULT BrsFolder_OnNotify( browse_info *info, UINT CtlID, LPNMHDR lpnmh )
616 {
617     NMTREEVIEWW *pnmtv = (NMTREEVIEWW *)lpnmh;
618
619     TRACE("%p %x %p msg=%x\n", info, CtlID, lpnmh, pnmtv->hdr.code);
620
621     if (pnmtv->hdr.idFrom != IDD_TREEVIEW)
622         return 0;
623
624     switch (pnmtv->hdr.code)
625     {
626     case TVN_DELETEITEMA:
627     case TVN_DELETEITEMW:
628         return BrsFolder_Treeview_Delete( info, pnmtv );
629
630     case TVN_ITEMEXPANDINGA:
631     case TVN_ITEMEXPANDINGW:
632         return BrsFolder_Treeview_Expand( info, pnmtv );
633
634     case TVN_SELCHANGEDA:
635     case TVN_SELCHANGEDW:
636         return BrsFolder_Treeview_Changed( info, pnmtv );
637
638     case TVN_ENDLABELEDITA:
639     case TVN_ENDLABELEDITW:
640         return BrsFolder_Treeview_Rename( info, (LPNMTVDISPINFOW)pnmtv );
641
642     default:
643         WARN("unhandled (%d)\n", pnmtv->hdr.code);
644         break;
645     }
646
647     return 0;
648 }
649
650
651 static BOOL BrsFolder_OnCreate( HWND hWnd, browse_info *info )
652 {
653     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
654
655     info->hWnd = hWnd;
656     SetPropW( hWnd, szBrowseFolderInfo, info );
657
658     if (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
659         FIXME("flags BIF_NEWDIALOGSTYLE partially implemented\n");
660     if (lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS)
661         FIXME("flags %x not implemented\n", lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS);
662
663     if (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
664     {
665         RECT rcWnd;
666
667         info->layout = LayoutInit(hWnd, g_layout_info, LAYOUT_INFO_COUNT);
668
669         /* TODO: Windows allows shrinking the windows a bit */
670         GetWindowRect(hWnd, &rcWnd);
671         info->szMin.cx = rcWnd.right - rcWnd.left;
672         info->szMin.cy = rcWnd.bottom - rcWnd.top;
673     }
674     else
675     {
676         info->layout = NULL;
677     }
678
679     if (lpBrowseInfo->lpszTitle)
680         SetWindowTextW( GetDlgItem(hWnd, IDD_TITLE), lpBrowseInfo->lpszTitle );
681     else
682         ShowWindow( GetDlgItem(hWnd, IDD_TITLE), SW_HIDE );
683
684     if (!(lpBrowseInfo->ulFlags & BIF_STATUSTEXT)
685         || (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE))
686         ShowWindow( GetDlgItem(hWnd, IDD_STATUS), SW_HIDE );
687
688     /* Hide "Make New Folder" Button? */
689     if ((lpBrowseInfo->ulFlags & BIF_NONEWFOLDERBUTTON)
690         || !(lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE))
691         ShowWindow( GetDlgItem(hWnd, IDD_MAKENEWFOLDER), SW_HIDE );
692
693     /* Hide the editbox? */
694     if (!(lpBrowseInfo->ulFlags & BIF_EDITBOX))
695     {
696         ShowWindow( GetDlgItem(hWnd, IDD_FOLDER), SW_HIDE );
697         ShowWindow( GetDlgItem(hWnd, IDD_FOLDERTEXT), SW_HIDE );
698     }
699
700     info->hwndTreeView = GetDlgItem( hWnd, IDD_TREEVIEW );
701     if (info->hwndTreeView)
702     {
703         InitializeTreeView( info );
704
705         /* Resize the treeview if there's not editbox */
706         if ((lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
707             && !(lpBrowseInfo->ulFlags & BIF_EDITBOX))
708         {
709             RECT rc;
710             GetClientRect(info->hwndTreeView, &rc);
711             SetWindowPos(info->hwndTreeView, HWND_TOP, 0, 0,
712                          rc.right, rc.bottom + 40, SWP_NOMOVE);
713         }
714     }
715     else
716         ERR("treeview control missing!\n");
717
718     browsefolder_callback( info->lpBrowseInfo, hWnd, BFFM_INITIALIZED, 0 );
719
720     return TRUE;
721 }
722
723 static HRESULT BrsFolder_Rename(browse_info *info, HTREEITEM rename)
724 {
725     SendMessageW(info->hwndTreeView, TVM_SELECTITEM, TVGN_CARET, (LPARAM)rename);
726     SendMessageW(info->hwndTreeView, TVM_EDITLABELW, 0, (LPARAM)rename);
727     return S_OK;
728 }
729
730 static HRESULT BrsFolder_NewFolder(browse_info *info)
731 {
732     DWORD flags = BrowseFlagsToSHCONTF(info->lpBrowseInfo->ulFlags);
733     IShellFolder *desktop, *cur;
734     ISFHelper *sfhelper;
735     WCHAR name[MAX_PATH];
736     HTREEITEM parent, added;
737     LPTV_ITEMDATA item_data;
738     LPITEMIDLIST new_item;
739     TVITEMW item;
740     HRESULT hr;
741     int len;
742
743     if(!info->pidlRet) {
744         ERR("Make new folder button should be disabled\n");
745         return E_FAIL;
746     }
747
748     /* Create new directory */
749     hr = SHGetDesktopFolder(&desktop);
750     if(FAILED(hr))
751         return hr;
752     hr = IShellFolder_BindToObject(desktop, info->pidlRet, 0, &IID_IShellFolder, (void**)&cur);
753     IShellFolder_Release(desktop);
754     if(FAILED(hr))
755         return hr;
756
757     hr = IShellFolder_QueryInterface(cur, &IID_ISFHelper, (void**)&sfhelper);
758     if(FAILED(hr))
759         return hr;
760
761     hr = SHGetPathFromIDListW(info->pidlRet, name);
762     if(FAILED(hr))
763         goto cleanup;
764
765     len = strlenW(name);
766     if(len<MAX_PATH)
767         name[len++] = '\\';
768     hr = ISFHelper_GetUniqueName(sfhelper, &name[len], MAX_PATH-len);
769     ISFHelper_Release(sfhelper);
770     if(FAILED(hr))
771         goto cleanup;
772
773     hr = E_FAIL;
774     if(!CreateDirectoryW(name, NULL))
775         goto cleanup;
776
777     /* Update parent of newly created directory */
778     parent = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CARET, 0);
779     if(!parent)
780         goto cleanup;
781
782     SendMessageW(info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)parent);
783
784     memset(&item, 0, sizeof(TVITEMW));
785     item.mask = TVIF_PARAM|TVIF_STATE;
786     item.hItem = parent;
787     SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
788     item_data = (LPTV_ITEMDATA)item.lParam;
789     if(!item_data)
790         goto cleanup;
791
792     if(item_data->pEnumIL)
793         IEnumIDList_Release(item_data->pEnumIL);
794     hr = IShellFolder_EnumObjects(cur, info->hwndTreeView, flags, &item_data->pEnumIL);
795     if(FAILED(hr))
796         goto cleanup;
797
798     /* Update treeview */
799     if(!(item.state&TVIS_EXPANDEDONCE)) {
800         item.mask = TVIF_STATE;
801         item.state = TVIS_EXPANDEDONCE;
802         item.stateMask = TVIS_EXPANDEDONCE;
803         SendMessageW(info->hwndTreeView, TVM_SETITEMW, 0, (LPARAM)&item);
804     }
805
806     hr = IShellFolder_ParseDisplayName(cur, NULL, NULL, name+len, NULL, &new_item, NULL);
807     if(FAILED(hr))
808         goto cleanup;
809
810     added = InsertTreeViewItem(info, cur, new_item, item_data->lpifq, NULL, parent);
811     IShellFolder_Release(cur);
812     SHFree(new_item);
813
814     SendMessageW(info->hwndTreeView, TVM_SORTCHILDREN, FALSE, (LPARAM)parent);
815     return BrsFolder_Rename(info, added);
816
817 cleanup:
818     return hr;
819 }
820
821 static BOOL BrsFolder_OnCommand( browse_info *info, UINT id )
822 {
823     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
824
825     switch (id)
826     {
827     case IDOK:
828         if (info->pidlRet == NULL) /* A null pidl would mean a cancel */
829             info->pidlRet = _ILCreateDesktop();
830         pdump( info->pidlRet );
831         if (lpBrowseInfo->pszDisplayName)
832             SHGetPathFromIDListW( info->pidlRet, lpBrowseInfo->pszDisplayName );
833         EndDialog( info->hWnd, 1 );
834         return TRUE;
835
836     case IDCANCEL:
837         EndDialog( info->hWnd, 0 );
838         return TRUE;
839
840     case IDD_MAKENEWFOLDER:
841         BrsFolder_NewFolder(info);
842         return TRUE;
843     }
844     return FALSE;
845 }
846
847 static BOOL BrsFolder_OnSetExpanded(browse_info *info, LPVOID selection, 
848     BOOL is_str, HTREEITEM *pItem)
849 {
850     LPITEMIDLIST pidlSelection = selection;
851     LPCITEMIDLIST pidlCurrent, pidlRoot;
852     TVITEMEXW item;
853     BOOL bResult = FALSE;
854
855     memset(&item, 0, sizeof(item));
856
857     /* If 'selection' is a string, convert to a Shell ID List. */ 
858     if (is_str) {
859         IShellFolder *psfDesktop;
860         HRESULT hr;
861
862         hr = SHGetDesktopFolder(&psfDesktop);
863         if (FAILED(hr))
864             goto done;
865
866         hr = IShellFolder_ParseDisplayName(psfDesktop, NULL, NULL, 
867                      selection, NULL, &pidlSelection, NULL);
868         IShellFolder_Release(psfDesktop);
869         if (FAILED(hr)) 
870             goto done;
871     }
872
873     /* Move pidlCurrent behind the SHITEMIDs in pidlSelection, which are the root of
874      * the sub-tree currently displayed. */
875     pidlRoot = info->lpBrowseInfo->pidlRoot;
876     pidlCurrent = pidlSelection;
877     while (!_ILIsEmpty(pidlRoot) && _ILIsEqualSimple(pidlRoot, pidlCurrent)) {
878         pidlRoot = ILGetNext(pidlRoot);
879         pidlCurrent = ILGetNext(pidlCurrent);
880     }
881
882     /* The given ID List is not part of the SHBrowseForFolder's current sub-tree. */
883     if (!_ILIsEmpty(pidlRoot))
884         goto done;
885
886     /* Initialize item to point to the first child of the root folder. */
887     item.mask = TVIF_PARAM;
888     item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_ROOT, 0);
889
890     if (item.hItem)
891         item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CHILD,
892                                              (LPARAM)item.hItem);
893
894     /* Walk the tree along the nodes corresponding to the remaining ITEMIDLIST */
895     while (item.hItem && !_ILIsEmpty(pidlCurrent)) {
896         LPTV_ITEMDATA pItemData;
897
898         SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
899         pItemData = (LPTV_ITEMDATA)item.lParam;
900
901         if (_ILIsEqualSimple(pItemData->lpi, pidlCurrent)) {
902             pidlCurrent = ILGetNext(pidlCurrent);
903             if (!_ILIsEmpty(pidlCurrent)) {
904                 /* Only expand current node and move on to it's first child,
905                  * if we didn't already reach the last SHITEMID */
906                 SendMessageW(info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item.hItem);
907                 item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CHILD,
908                                              (LPARAM)item.hItem);
909             }
910         } else {
911             item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_NEXT,
912                                              (LPARAM)item.hItem);
913         }
914     }
915
916     if (_ILIsEmpty(pidlCurrent) && item.hItem) 
917         bResult = TRUE;
918
919 done:
920     if (pidlSelection && pidlSelection != selection)
921         ILFree(pidlSelection);
922
923     if (pItem) 
924         *pItem = item.hItem;
925     
926     return bResult;
927 }
928
929 static BOOL BrsFolder_OnSetSelectionW(browse_info *info, LPVOID selection, BOOL is_str) {
930     HTREEITEM hItem;
931     BOOL bResult;
932
933     if (!selection) return FALSE;
934
935     bResult = BrsFolder_OnSetExpanded(info, selection, is_str, &hItem);
936     if (bResult)
937         SendMessageW(info->hwndTreeView, TVM_SELECTITEM, TVGN_CARET, (LPARAM)hItem );
938     return bResult;
939 }
940
941 static BOOL BrsFolder_OnSetSelectionA(browse_info *info, LPVOID selection, BOOL is_str) {
942     LPWSTR selectionW = NULL;
943     BOOL result = FALSE;
944     int length;
945     
946     if (!is_str)
947         return BrsFolder_OnSetSelectionW(info, selection, is_str);
948
949     if ((length = MultiByteToWideChar(CP_ACP, 0, selection, -1, NULL, 0)) &&
950         (selectionW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR))) &&
951         MultiByteToWideChar(CP_ACP, 0, selection, -1, selectionW, length))
952     {
953         result = BrsFolder_OnSetSelectionW(info, selectionW, is_str);
954     }
955
956     HeapFree(GetProcessHeap(), 0, selectionW);
957     return result;
958 }
959
960 static BOOL BrsFolder_OnWindowPosChanging(browse_info *info, WINDOWPOS *pos)
961 {
962     if ((info->lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE) && !(pos->flags & SWP_NOSIZE))
963     {
964         if (pos->cx < info->szMin.cx)
965             pos->cx = info->szMin.cx;
966         if (pos->cy < info->szMin.cy)
967             pos->cy = info->szMin.cy;
968     }
969     return 0;
970 }
971
972 static INT BrsFolder_OnDestroy(browse_info *info)
973 {
974     if (info->layout)
975     {
976         SHFree(info->layout);
977         info->layout = NULL;
978     }
979
980     return 0;
981 }
982
983 /*************************************************************************
984  *             BrsFolderDlgProc32  (not an exported API function)
985  */
986 static INT_PTR CALLBACK BrsFolderDlgProc( HWND hWnd, UINT msg, WPARAM wParam,
987                                           LPARAM lParam )
988 {
989     browse_info *info;
990
991     TRACE("hwnd=%p msg=%04x 0x%08lx 0x%08lx\n", hWnd, msg, wParam, lParam );
992
993     if (msg == WM_INITDIALOG)
994         return BrsFolder_OnCreate( hWnd, (browse_info*) lParam );
995
996     info = GetPropW( hWnd, szBrowseFolderInfo );
997
998     switch (msg)
999     {
1000     case WM_NOTIFY:
1001         return BrsFolder_OnNotify( info, (UINT)wParam, (LPNMHDR)lParam);
1002
1003     case WM_COMMAND:
1004         return BrsFolder_OnCommand( info, wParam );
1005
1006     case WM_WINDOWPOSCHANGING:
1007         return BrsFolder_OnWindowPosChanging( info, (WINDOWPOS *)lParam);
1008
1009     case WM_SIZE:
1010         if (info->layout)  /* new style dialogs */
1011             LayoutUpdate(hWnd, info->layout, g_layout_info, LAYOUT_INFO_COUNT);
1012         return 0;
1013
1014     case BFFM_SETSTATUSTEXTA:
1015         TRACE("Set status %s\n", debugstr_a((LPSTR)lParam));
1016         SetWindowTextA(GetDlgItem(hWnd, IDD_STATUS), (LPSTR)lParam);
1017         break;
1018
1019     case BFFM_SETSTATUSTEXTW:
1020         TRACE("Set status %s\n", debugstr_w((LPWSTR)lParam));
1021         SetWindowTextW(GetDlgItem(hWnd, IDD_STATUS), (LPWSTR)lParam);
1022         break;
1023
1024     case BFFM_ENABLEOK:
1025         TRACE("Enable %ld\n", lParam);
1026         EnableWindow(GetDlgItem(hWnd, 1), lParam != 0);
1027         break;
1028
1029     case BFFM_SETOKTEXT: /* unicode only */
1030         TRACE("Set OK text %s\n", debugstr_w((LPWSTR)wParam));
1031         SetWindowTextW(GetDlgItem(hWnd, 1), (LPWSTR)wParam);
1032         break;
1033
1034     case BFFM_SETSELECTIONA:
1035         return BrsFolder_OnSetSelectionA(info, (LPVOID)lParam, (BOOL)wParam);
1036
1037     case BFFM_SETSELECTIONW:
1038         return BrsFolder_OnSetSelectionW(info, (LPVOID)lParam, (BOOL)wParam);
1039
1040     case BFFM_SETEXPANDED: /* unicode only */
1041         return BrsFolder_OnSetExpanded(info, (LPVOID)lParam, (BOOL)wParam, NULL);
1042
1043     case WM_DESTROY:
1044         return BrsFolder_OnDestroy(info);
1045     }
1046     return FALSE;
1047 }
1048
1049 static const WCHAR swBrowseTemplateName[] = {
1050     'S','H','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
1051 static const WCHAR swNewBrowseTemplateName[] = {
1052     'S','H','N','E','W','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
1053
1054 /*************************************************************************
1055  * SHBrowseForFolderA [SHELL32.@]
1056  * SHBrowseForFolder  [SHELL32.@]
1057  */
1058 LPITEMIDLIST WINAPI SHBrowseForFolderA (LPBROWSEINFOA lpbi)
1059 {
1060     BROWSEINFOW bi;
1061     LPITEMIDLIST lpid;
1062     INT len;
1063     LPWSTR title;
1064
1065     TRACE("%p\n", lpbi);
1066
1067     bi.hwndOwner = lpbi->hwndOwner;
1068     bi.pidlRoot = lpbi->pidlRoot;
1069     if (lpbi->pszDisplayName)
1070         bi.pszDisplayName = HeapAlloc( GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR) );
1071     else
1072         bi.pszDisplayName = NULL;
1073
1074     if (lpbi->lpszTitle)
1075     {
1076         len = MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, NULL, 0 );
1077         title = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1078         MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, title, len );
1079     }
1080     else
1081         title = NULL;
1082
1083     bi.lpszTitle = title;
1084     bi.ulFlags = lpbi->ulFlags;
1085     bi.lpfn = lpbi->lpfn;
1086     bi.lParam = lpbi->lParam;
1087     bi.iImage = lpbi->iImage;
1088     lpid = SHBrowseForFolderW( &bi );
1089     if (bi.pszDisplayName)
1090     {
1091         WideCharToMultiByte( CP_ACP, 0, bi.pszDisplayName, -1,
1092                              lpbi->pszDisplayName, MAX_PATH, 0, NULL);
1093         HeapFree( GetProcessHeap(), 0, bi.pszDisplayName );
1094     }
1095     HeapFree(GetProcessHeap(), 0, title);
1096     lpbi->iImage = bi.iImage;
1097     return lpid;
1098 }
1099
1100
1101 /*************************************************************************
1102  * SHBrowseForFolderW [SHELL32.@]
1103  *
1104  * NOTES
1105  *  crashes when passed a null pointer
1106  */
1107 LPITEMIDLIST WINAPI SHBrowseForFolderW (LPBROWSEINFOW lpbi)
1108 {
1109     browse_info info;
1110     DWORD r;
1111     HRESULT hr;
1112     const WCHAR * templateName;
1113
1114     info.hWnd = 0;
1115     info.pidlRet = NULL;
1116     info.lpBrowseInfo = lpbi;
1117     info.hwndTreeView = NULL;
1118
1119     hr = OleInitialize(NULL);
1120
1121     if (lpbi->ulFlags & BIF_NEWDIALOGSTYLE)
1122         templateName = swNewBrowseTemplateName;
1123     else
1124         templateName = swBrowseTemplateName;
1125     r = DialogBoxParamW( shell32_hInstance, templateName, lpbi->hwndOwner,
1126                          BrsFolderDlgProc, (LPARAM)&info );
1127     if (SUCCEEDED(hr)) 
1128         OleUninitialize();
1129     if (!r)
1130     {
1131         ILFree(info.pidlRet);
1132         return NULL;
1133     }
1134
1135     return info.pidlRet;
1136 }