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