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