d3d9: Implement IDirect3DVertexBuffer9 private data handling on top of wined3d_resource.
[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             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         lptvid = SHAlloc( sizeof(TV_ITEMDATA) );
373         if (!lptvid)
374             return NULL;
375
376         if (!GetName(lpsf, pidl, SHGDN_NORMAL, szBuff))
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         HTREEITEM       hPrev = 0;
414         LPITEMIDLIST    pidlTemp = 0;
415         ULONG           ulFetched;
416         HRESULT         hr;
417         HWND            hwnd = GetParent( info->hwndTreeView );
418
419         TRACE("%p %p %p %p\n",lpsf, pidl, hParent, lpe);
420
421         /* No IEnumIDList -> No children */
422         if (!lpe) return;
423         
424         SetCapture( hwnd );
425         SetCursor( LoadCursorA( 0, (LPSTR)IDC_WAIT ) );
426
427         while (S_OK == IEnumIDList_Next(lpe,1,&pidlTemp,&ulFetched))
428         {
429             ULONG ulAttrs = SFGAO_HASSUBFOLDER | SFGAO_FOLDER;
430             IEnumIDList* pEnumIL = NULL;
431             IShellFolder* pSFChild = NULL;
432             IShellFolder_GetAttributesOf(lpsf, 1, (LPCITEMIDLIST*)&pidlTemp, &ulAttrs);
433             if (ulAttrs & SFGAO_FOLDER)
434             {
435                 hr = IShellFolder_BindToObject(lpsf,pidlTemp,NULL,&IID_IShellFolder,(LPVOID*)&pSFChild);
436                 if (SUCCEEDED(hr))
437                 {
438                     DWORD flags = BrowseFlagsToSHCONTF(info->lpBrowseInfo->ulFlags);
439                     hr = IShellFolder_EnumObjects(pSFChild, hwnd, flags, &pEnumIL);
440                     if (hr == S_OK)
441                     {
442                         if ((IEnumIDList_Skip(pEnumIL, 1) != S_OK) ||
443                              FAILED(IEnumIDList_Reset(pEnumIL)))
444                         {
445                             IEnumIDList_Release(pEnumIL);
446                             pEnumIL = NULL;
447                         }
448                     }
449                     IShellFolder_Release(pSFChild);
450                 }
451             }
452
453             if (!(hPrev = InsertTreeViewItem(info, lpsf, pidlTemp, pidl, pEnumIL, hParent)))
454                 goto done;
455             SHFree(pidlTemp);  /* Finally, free the pidl that the shell gave us... */
456             pidlTemp=NULL;
457         }
458
459 done:
460         ReleaseCapture();
461         SetCursor(LoadCursorW(0, (LPWSTR)IDC_ARROW));
462     SHFree(pidlTemp);
463 }
464
465 static inline BOOL PIDLIsType(LPCITEMIDLIST pidl, PIDLTYPE type)
466 {
467     LPPIDLDATA data = _ILGetDataPointer(pidl);
468     if (!data)
469         return FALSE;
470     return (data->type == type);
471 }
472
473 static void BrsFolder_CheckValidSelection( browse_info *info, LPTV_ITEMDATA lptvid )
474 {
475     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
476     LPCITEMIDLIST pidl = lptvid->lpi;
477     BOOL bEnabled = TRUE;
478     DWORD dwAttributes;
479     HRESULT r;
480
481     if ((lpBrowseInfo->ulFlags & BIF_BROWSEFORCOMPUTER) &&
482         !PIDLIsType(pidl, PT_COMP))
483         bEnabled = FALSE;
484     if (lpBrowseInfo->ulFlags & BIF_RETURNFSANCESTORS)
485     {
486         dwAttributes = SFGAO_FILESYSANCESTOR | SFGAO_FILESYSTEM;
487         r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
488                                 (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
489         if (FAILED(r) || !(dwAttributes & (SFGAO_FILESYSANCESTOR|SFGAO_FILESYSTEM)))
490             bEnabled = FALSE;
491     }
492     if (lpBrowseInfo->ulFlags & BIF_RETURNONLYFSDIRS)
493     {
494         dwAttributes = SFGAO_FOLDER | SFGAO_FILESYSTEM;
495         r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
496                                 (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
497         if (FAILED(r) || 
498             ((dwAttributes & (SFGAO_FOLDER|SFGAO_FILESYSTEM)) != (SFGAO_FOLDER|SFGAO_FILESYSTEM)))
499         {
500             bEnabled = FALSE;
501         }
502     }
503     SendMessageW(info->hWnd, BFFM_ENABLEOK, 0, bEnabled);
504 }
505
506 static LRESULT BrsFolder_Treeview_Delete( browse_info *info, NMTREEVIEWW *pnmtv )
507 {
508     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA)pnmtv->itemOld.lParam;
509
510     TRACE("TVN_DELETEITEMA/W %p\n", lptvid);
511
512     IShellFolder_Release(lptvid->lpsfParent);
513     if (lptvid->pEnumIL)
514         IEnumIDList_Release(lptvid->pEnumIL);
515     SHFree(lptvid->lpi);
516     SHFree(lptvid->lpifq);
517     SHFree(lptvid);
518     return 0;
519 }
520
521 static LRESULT BrsFolder_Treeview_Expand( browse_info *info, NMTREEVIEWW *pnmtv )
522 {
523     IShellFolder *lpsf2 = NULL;
524     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
525     HRESULT r;
526
527     TRACE("TVN_ITEMEXPANDINGA/W\n");
528
529     if ((pnmtv->itemNew.state & TVIS_EXPANDEDONCE))
530         return 0;
531
532     if (!_ILIsEmpty(lptvid->lpi)) {
533         r = IShellFolder_BindToObject( lptvid->lpsfParent, lptvid->lpi, 0,
534                                        &IID_IShellFolder, (void**)&lpsf2 );
535     } else {
536         lpsf2 = lptvid->lpsfParent;
537         IShellFolder_AddRef(lpsf2);
538         r = S_OK;
539     }
540
541     if (SUCCEEDED(r))
542     {
543         FillTreeView( info, lpsf2, lptvid->lpifq, pnmtv->itemNew.hItem, lptvid->pEnumIL);
544         IShellFolder_Release( lpsf2 );
545     }
546
547     /* My Computer is already sorted and trying to do a simple text
548      * sort will only mess things up */
549     if (!_ILIsMyComputer(lptvid->lpi))
550         SendMessageW( info->hwndTreeView, TVM_SORTCHILDREN,
551                       FALSE, (LPARAM)pnmtv->itemNew.hItem );
552
553     return 0;
554 }
555
556 static HRESULT BrsFolder_Treeview_Changed( browse_info *info, NMTREEVIEWW *pnmtv )
557 {
558     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
559
560     lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
561     ILFree(info->pidlRet);
562     info->pidlRet = ILClone(lptvid->lpifq);
563     browsefolder_callback( info->lpBrowseInfo, info->hWnd, BFFM_SELCHANGED,
564                            (LPARAM)info->pidlRet );
565     BrsFolder_CheckValidSelection( info, lptvid );
566     return 0;
567 }
568
569 static LRESULT BrsFolder_OnNotify( browse_info *info, UINT CtlID, LPNMHDR lpnmh )
570 {
571     NMTREEVIEWW *pnmtv = (NMTREEVIEWW *)lpnmh;
572
573     TRACE("%p %x %p msg=%x\n", info, CtlID, lpnmh, pnmtv->hdr.code);
574
575     if (pnmtv->hdr.idFrom != IDD_TREEVIEW)
576         return 0;
577
578     switch (pnmtv->hdr.code)
579     {
580     case TVN_DELETEITEMA:
581     case TVN_DELETEITEMW:
582         return BrsFolder_Treeview_Delete( info, pnmtv );
583
584     case TVN_ITEMEXPANDINGA:
585     case TVN_ITEMEXPANDINGW:
586         return BrsFolder_Treeview_Expand( info, pnmtv );
587
588     case TVN_SELCHANGEDA:
589     case TVN_SELCHANGEDW:
590         return BrsFolder_Treeview_Changed( info, pnmtv );
591
592     default:
593         WARN("unhandled (%d)\n", pnmtv->hdr.code);
594         break;
595     }
596
597     return 0;
598 }
599
600
601 static BOOL BrsFolder_OnCreate( HWND hWnd, browse_info *info )
602 {
603     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
604
605     info->hWnd = hWnd;
606     SetPropW( hWnd, szBrowseFolderInfo, info );
607
608     if (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
609         FIXME("flags BIF_NEWDIALOGSTYLE partially implemented\n");
610     if (lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS)
611         FIXME("flags %x not implemented\n", lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS);
612
613     if (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
614     {
615         RECT rcWnd;
616
617         info->layout = LayoutInit(hWnd, g_layout_info, LAYOUT_INFO_COUNT);
618
619         /* TODO: Windows allows shrinking the windows a bit */
620         GetWindowRect(hWnd, &rcWnd);
621         info->szMin.cx = rcWnd.right - rcWnd.left;
622         info->szMin.cy = rcWnd.bottom - rcWnd.top;
623     }
624     else
625     {
626         info->layout = NULL;
627     }
628
629     if (lpBrowseInfo->lpszTitle)
630         SetWindowTextW( GetDlgItem(hWnd, IDD_TITLE), lpBrowseInfo->lpszTitle );
631     else
632         ShowWindow( GetDlgItem(hWnd, IDD_TITLE), SW_HIDE );
633
634     if (!(lpBrowseInfo->ulFlags & BIF_STATUSTEXT)
635         || (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE))
636         ShowWindow( GetDlgItem(hWnd, IDD_STATUS), SW_HIDE );
637
638     /* Hide "Make New Folder" Button? */
639     if ((lpBrowseInfo->ulFlags & BIF_NONEWFOLDERBUTTON)
640         || !(lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE))
641         ShowWindow( GetDlgItem(hWnd, IDD_MAKENEWFOLDER), SW_HIDE );
642
643     /* Hide the editbox? */
644     if (!(lpBrowseInfo->ulFlags & BIF_EDITBOX))
645     {
646         ShowWindow( GetDlgItem(hWnd, IDD_FOLDER), SW_HIDE );
647         ShowWindow( GetDlgItem(hWnd, IDD_FOLDERTEXT), SW_HIDE );
648     }
649
650     info->hwndTreeView = GetDlgItem( hWnd, IDD_TREEVIEW );
651     if (info->hwndTreeView)
652     {
653         InitializeTreeView( info );
654
655         /* Resize the treeview if there's not editbox */
656         if ((lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
657             && !(lpBrowseInfo->ulFlags & BIF_EDITBOX))
658         {
659             RECT rc;
660             GetClientRect(info->hwndTreeView, &rc);
661             SetWindowPos(info->hwndTreeView, HWND_TOP, 0, 0,
662                          rc.right, rc.bottom + 40, SWP_NOMOVE);
663         }
664     }
665     else
666         ERR("treeview control missing!\n");
667
668     browsefolder_callback( info->lpBrowseInfo, hWnd, BFFM_INITIALIZED, 0 );
669
670     return TRUE;
671 }
672
673 static BOOL BrsFolder_OnCommand( browse_info *info, UINT id )
674 {
675     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
676
677     switch (id)
678     {
679     case IDOK:
680         if (info->pidlRet == NULL) /* A null pidl would mean a cancel */
681             info->pidlRet = _ILCreateDesktop();
682         pdump( info->pidlRet );
683         if (lpBrowseInfo->pszDisplayName)
684             SHGetPathFromIDListW( info->pidlRet, lpBrowseInfo->pszDisplayName );
685         EndDialog( info->hWnd, 1 );
686         return TRUE;
687
688     case IDCANCEL:
689         EndDialog( info->hWnd, 0 );
690         return TRUE;
691
692     case IDD_MAKENEWFOLDER:
693         FIXME("make new folder not implemented\n");
694         return TRUE;
695     }
696     return FALSE;
697 }
698
699 static BOOL BrsFolder_OnSetExpanded(browse_info *info, LPVOID selection, 
700     BOOL is_str, HTREEITEM *pItem)
701 {
702     LPITEMIDLIST pidlSelection = selection;
703     LPCITEMIDLIST pidlCurrent, pidlRoot;
704     TVITEMEXW item;
705     BOOL bResult = FALSE;
706     
707     /* If 'selection' is a string, convert to a Shell ID List. */ 
708     if (is_str) {
709         IShellFolder *psfDesktop;
710         HRESULT hr;
711
712         hr = SHGetDesktopFolder(&psfDesktop);
713         if (FAILED(hr))
714             goto done;
715
716         hr = IShellFolder_ParseDisplayName(psfDesktop, NULL, NULL, 
717                      selection, NULL, &pidlSelection, NULL);
718         IShellFolder_Release(psfDesktop);
719         if (FAILED(hr)) 
720             goto done;
721     }
722
723     /* Move pidlCurrent behind the SHITEMIDs in pidlSelection, which are the root of
724      * the sub-tree currently displayed. */
725     pidlRoot = info->lpBrowseInfo->pidlRoot;
726     pidlCurrent = pidlSelection;
727     while (!_ILIsEmpty(pidlRoot) && _ILIsEqualSimple(pidlRoot, pidlCurrent)) {
728         pidlRoot = ILGetNext(pidlRoot);
729         pidlCurrent = ILGetNext(pidlCurrent);
730     }
731
732     /* The given ID List is not part of the SHBrowseForFolder's current sub-tree. */
733     if (!_ILIsEmpty(pidlRoot))
734         goto done;
735
736     /* Initialize item to point to the first child of the root folder. */
737     memset(&item, 0, sizeof(item));
738     item.mask = TVIF_PARAM;
739     item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_ROOT, 0);
740
741     if (item.hItem)
742         item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CHILD,
743                                              (LPARAM)item.hItem);
744
745     /* Walk the tree along the nodes corresponding to the remaining ITEMIDLIST */
746     while (item.hItem && !_ILIsEmpty(pidlCurrent)) {
747         LPTV_ITEMDATA pItemData;
748
749         SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
750         pItemData = (LPTV_ITEMDATA)item.lParam;
751
752         if (_ILIsEqualSimple(pItemData->lpi, pidlCurrent)) {
753             pidlCurrent = ILGetNext(pidlCurrent);
754             if (!_ILIsEmpty(pidlCurrent)) {
755                 /* Only expand current node and move on to it's first child,
756                  * if we didn't already reach the last SHITEMID */
757                 SendMessageW(info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item.hItem);
758                 item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CHILD,
759                                              (LPARAM)item.hItem);
760             }
761         } else {
762             item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_NEXT,
763                                              (LPARAM)item.hItem);
764         }
765     }
766
767     if (_ILIsEmpty(pidlCurrent) && item.hItem) 
768         bResult = TRUE;
769
770 done:
771     if (pidlSelection && pidlSelection != selection)
772         ILFree(pidlSelection);
773
774     if (pItem) 
775         *pItem = item.hItem;
776     
777     return bResult;
778 }
779
780 static BOOL BrsFolder_OnSetSelectionW(browse_info *info, LPVOID selection, BOOL is_str) {
781     HTREEITEM hItem;
782     BOOL bResult;
783
784     if (!selection) return FALSE;
785
786     bResult = BrsFolder_OnSetExpanded(info, selection, is_str, &hItem);
787     if (bResult)
788         SendMessageW(info->hwndTreeView, TVM_SELECTITEM, TVGN_CARET, (LPARAM)hItem );
789     return bResult;
790 }
791
792 static BOOL BrsFolder_OnSetSelectionA(browse_info *info, LPVOID selection, BOOL is_str) {
793     LPWSTR selectionW = NULL;
794     BOOL result = FALSE;
795     int length;
796     
797     if (!is_str)
798         return BrsFolder_OnSetSelectionW(info, selection, is_str);
799
800     if ((length = MultiByteToWideChar(CP_ACP, 0, selection, -1, NULL, 0)) &&
801         (selectionW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR))) &&
802         MultiByteToWideChar(CP_ACP, 0, selection, -1, selectionW, length))
803     {
804         result = BrsFolder_OnSetSelectionW(info, selectionW, is_str);
805     }
806
807     HeapFree(GetProcessHeap(), 0, selectionW);
808     return result;
809 }
810
811 static BOOL BrsFolder_OnWindowPosChanging(browse_info *info, WINDOWPOS *pos)
812 {
813     if ((info->lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE) && !(pos->flags & SWP_NOSIZE))
814     {
815         if (pos->cx < info->szMin.cx)
816             pos->cx = info->szMin.cx;
817         if (pos->cy < info->szMin.cy)
818             pos->cy = info->szMin.cy;
819     }
820     return 0;
821 }
822
823 static INT BrsFolder_OnDestroy(browse_info *info)
824 {
825     if (info->layout)
826     {
827         SHFree(info->layout);
828         info->layout = NULL;
829     }
830
831     return 0;
832 }
833
834 /*************************************************************************
835  *             BrsFolderDlgProc32  (not an exported API function)
836  */
837 static INT_PTR CALLBACK BrsFolderDlgProc( HWND hWnd, UINT msg, WPARAM wParam,
838                                           LPARAM lParam )
839 {
840     browse_info *info;
841
842     TRACE("hwnd=%p msg=%04x 0x%08lx 0x%08lx\n", hWnd, msg, wParam, lParam );
843
844     if (msg == WM_INITDIALOG)
845         return BrsFolder_OnCreate( hWnd, (browse_info*) lParam );
846
847     info = GetPropW( hWnd, szBrowseFolderInfo );
848
849     switch (msg)
850     {
851     case WM_NOTIFY:
852         return BrsFolder_OnNotify( info, (UINT)wParam, (LPNMHDR)lParam);
853
854     case WM_COMMAND:
855         return BrsFolder_OnCommand( info, wParam );
856
857     case WM_WINDOWPOSCHANGING:
858         return BrsFolder_OnWindowPosChanging( info, (WINDOWPOS *)lParam);
859
860     case WM_SIZE:
861         if (info->layout)  /* new style dialogs */
862             LayoutUpdate(hWnd, info->layout, g_layout_info, LAYOUT_INFO_COUNT);
863         return 0;
864
865     case BFFM_SETSTATUSTEXTA:
866         TRACE("Set status %s\n", debugstr_a((LPSTR)lParam));
867         SetWindowTextA(GetDlgItem(hWnd, IDD_STATUS), (LPSTR)lParam);
868         break;
869
870     case BFFM_SETSTATUSTEXTW:
871         TRACE("Set status %s\n", debugstr_w((LPWSTR)lParam));
872         SetWindowTextW(GetDlgItem(hWnd, IDD_STATUS), (LPWSTR)lParam);
873         break;
874
875     case BFFM_ENABLEOK:
876         TRACE("Enable %ld\n", lParam);
877         EnableWindow(GetDlgItem(hWnd, 1), (lParam)?TRUE:FALSE);
878         break;
879
880     case BFFM_SETOKTEXT: /* unicode only */
881         TRACE("Set OK text %s\n", debugstr_w((LPWSTR)wParam));
882         SetWindowTextW(GetDlgItem(hWnd, 1), (LPWSTR)wParam);
883         break;
884
885     case BFFM_SETSELECTIONA:
886         return BrsFolder_OnSetSelectionA(info, (LPVOID)lParam, (BOOL)wParam);
887
888     case BFFM_SETSELECTIONW:
889         return BrsFolder_OnSetSelectionW(info, (LPVOID)lParam, (BOOL)wParam);
890
891     case BFFM_SETEXPANDED: /* unicode only */
892         return BrsFolder_OnSetExpanded(info, (LPVOID)lParam, (BOOL)wParam, NULL);
893
894     case WM_DESTROY:
895         return BrsFolder_OnDestroy(info);
896     }
897     return FALSE;
898 }
899
900 static const WCHAR swBrowseTemplateName[] = {
901     'S','H','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
902 static const WCHAR swNewBrowseTemplateName[] = {
903     'S','H','N','E','W','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
904
905 /*************************************************************************
906  * SHBrowseForFolderA [SHELL32.@]
907  * SHBrowseForFolder  [SHELL32.@]
908  */
909 LPITEMIDLIST WINAPI SHBrowseForFolderA (LPBROWSEINFOA lpbi)
910 {
911     BROWSEINFOW bi;
912     LPITEMIDLIST lpid;
913     INT len;
914     LPWSTR title;
915
916     TRACE("%p\n", lpbi);
917
918     bi.hwndOwner = lpbi->hwndOwner;
919     bi.pidlRoot = lpbi->pidlRoot;
920     if (lpbi->pszDisplayName)
921     {
922         bi.pszDisplayName = HeapAlloc( GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR) );
923         MultiByteToWideChar( CP_ACP, 0, lpbi->pszDisplayName, -1, bi.pszDisplayName, MAX_PATH );
924     }
925     else
926         bi.pszDisplayName = NULL;
927
928     if (lpbi->lpszTitle)
929     {
930         len = MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, NULL, 0 );
931         title = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
932         MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, title, len );
933     }
934     else
935         title = NULL;
936
937     bi.lpszTitle = title;
938     bi.ulFlags = lpbi->ulFlags;
939     bi.lpfn = lpbi->lpfn;
940     bi.lParam = lpbi->lParam;
941     bi.iImage = lpbi->iImage;
942     lpid = SHBrowseForFolderW( &bi );
943     if (bi.pszDisplayName)
944     {
945         WideCharToMultiByte( CP_ACP, 0, bi.pszDisplayName, -1,
946                              lpbi->pszDisplayName, MAX_PATH, 0, NULL);
947         HeapFree( GetProcessHeap(), 0, bi.pszDisplayName );
948     }
949     HeapFree(GetProcessHeap(), 0, title);
950     lpbi->iImage = bi.iImage;
951     return lpid;
952 }
953
954
955 /*************************************************************************
956  * SHBrowseForFolderW [SHELL32.@]
957  *
958  * NOTES
959  *  crashes when passed a null pointer
960  */
961 LPITEMIDLIST WINAPI SHBrowseForFolderW (LPBROWSEINFOW lpbi)
962 {
963     browse_info info;
964     DWORD r;
965     HRESULT hr;
966     const WCHAR * templateName;
967
968     info.hWnd = 0;
969     info.pidlRet = NULL;
970     info.lpBrowseInfo = lpbi;
971     info.hwndTreeView = NULL;
972
973     hr = OleInitialize(NULL);
974
975     if (lpbi->ulFlags & BIF_NEWDIALOGSTYLE)
976         templateName = swNewBrowseTemplateName;
977     else
978         templateName = swBrowseTemplateName;
979     r = DialogBoxParamW( shell32_hInstance, templateName, lpbi->hwndOwner,
980                          BrsFolderDlgProc, (LPARAM)&info );
981     if (SUCCEEDED(hr)) 
982         OleUninitialize();
983     if (!r)
984     {
985         ILFree(info.pidlRet);
986         return NULL;
987     }
988
989     return info.pidlRet;
990 }