Fixed copyright date.
[wine] / dlls / commdlg / filedlg95.c
1 /*
2  * COMMDLG - File Open Dialogs Win95 look and feel
3  *
4  * Copyright 1999 Francois Boisvert
5  * Copyright 1999, 2000 Juergen Schmied
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * FIXME: The whole concept of handling unicode is badly broken.
22  *      many hook-messages expecting a pointer to a
23  *      OPENFILENAMEA or W structure. With the current architecture
24  *      we would have to convert the beast at every call to a hook.
25  *      we have to find a better solution but if would likely cause
26  *      a complete rewrite with after we shouldhandle the
27  *      OPENFILENAME structure without any converting (jsch).
28  *
29  * FIXME: any hook gets a OPENFILENAMEA structure
30  *
31  * FIXME: CDN_FILEOK is wrong implemented, other CDN_ messages likely too
32  *
33  * FIXME: old style hook messages are not implemented (except FILEOKSTRING)
34  *
35  * FIXME: lpstrCustomFilter not handled
36  *
37  * FIXME: if the size of lpstrFile (nMaxFile) is too small the first
38  * two bytes of lpstrFile should contain the needed size
39  *
40  * FIXME: algorithm for selecting the initial directory is too simple
41  *
42  * FIXME: add to recent docs
43  *
44  * FIXME: flags not implemented: OFN_CREATEPROMPT, OFN_DONTADDTORECENT,
45  * OFN_ENABLEINCLUDENOTIFY, OFN_ENABLESIZING, OFN_EXTENSIONDIFFERENT,
46  * OFN_NODEREFERENCELINKS, OFN_NOREADONLYRETURN,
47  * OFN_NOTESTFILECREATE, OFN_OVERWRITEPROMPT, OFN_USEMONIKERS
48  *
49  * FIXME: lCustData for lpfnHook (WM_INITDIALOG)
50  *
51  *
52  */
53
54 #include "config.h"
55 #include "wine/port.h"
56
57 #include <ctype.h>
58 #include <stdlib.h>
59 #include <stdio.h>
60 #include <string.h>
61
62 #define NONAMELESSUNION
63 #define NONAMELESSSTRUCT
64 #include "winbase.h"
65 #include "winternl.h"
66 #include "winnls.h"
67 #include "wine/unicode.h"
68 #include "commdlg.h"
69 #include "dlgs.h"
70 #include "cdlg.h"
71 #include "wine/debug.h"
72 #include "cderr.h"
73 #include "shellapi.h"
74 #include "shlguid.h"
75 #include "filedlgbrowser.h"
76 #include "shlwapi.h"
77 #include "wine/obj_contextmenu.h"
78
79 WINE_DEFAULT_DEBUG_CHANNEL(commdlg);
80
81 #define UNIMPLEMENTED_FLAGS \
82 (OFN_CREATEPROMPT | OFN_DONTADDTORECENT |\
83 OFN_ENABLEINCLUDENOTIFY | OFN_ENABLESIZING | OFN_EXTENSIONDIFFERENT |\
84 OFN_NODEREFERENCELINKS | OFN_NOREADONLYRETURN |\
85 OFN_NOTESTFILECREATE | OFN_OVERWRITEPROMPT /*| OFN_USEMONIKERS*/)
86
87 #define IsHooked(fodInfos) \
88         ((fodInfos->ofnInfos->Flags & OFN_ENABLEHOOK) && fodInfos->ofnInfos->lpfnHook)
89 /***********************************************************************
90  * Data structure and global variables
91  */
92 typedef struct SFolder
93 {
94   int m_iImageIndex;    /* Index of picture in image list */
95   HIMAGELIST hImgList;
96   int m_iIndent;      /* Indentation index */
97   LPITEMIDLIST pidlItem;  /* absolute pidl of the item */
98
99 } SFOLDER,*LPSFOLDER;
100
101 typedef struct tagLookInInfo
102 {
103   int iMaxIndentation;
104   UINT uSelectedItem;
105 } LookInInfos;
106
107
108 /***********************************************************************
109  * Defines and global variables
110  */
111
112 /* Draw item constant */
113 #define ICONWIDTH 18
114 #define XTEXTOFFSET 3
115
116 /* AddItem flags*/
117 #define LISTEND -1
118
119 /* SearchItem methods */
120 #define SEARCH_PIDL 1
121 #define SEARCH_EXP  2
122 #define ITEM_NOTFOUND -1
123
124 /* Undefined windows message sent by CreateViewObject*/
125 #define WM_GETISHELLBROWSER  WM_USER+7
126
127 /* NOTE
128  * Those macros exist in windowsx.h. However, you can't really use them since
129  * they rely on the UNICODE defines and can't be used inside Wine itself.
130  */
131
132 /* Combo box macros */
133 #define CBAddString(hwnd,str) \
134   SendMessageA(hwnd,CB_ADDSTRING,0,(LPARAM)str);
135 #define CBAddStringW(hwnd,str) \
136   SendMessageW(hwnd,CB_ADDSTRING,0,(LPARAM)str);
137
138 #define CBInsertString(hwnd,str,pos) \
139   SendMessageA(hwnd,CB_INSERTSTRING,(WPARAM)pos,(LPARAM)str);
140
141 #define CBDeleteString(hwnd,pos) \
142   SendMessageA(hwnd,CB_DELETESTRING,(WPARAM)pos,0);
143
144 #define CBSetItemDataPtr(hwnd,iItemId,dataPtr) \
145   SendMessageA(hwnd,CB_SETITEMDATA,(WPARAM)iItemId,(LPARAM)dataPtr);
146
147 #define CBGetItemDataPtr(hwnd,iItemId) \
148   SendMessageA(hwnd,CB_GETITEMDATA,(WPARAM)iItemId,0)
149
150 #define CBGetLBText(hwnd,iItemId,str) \
151   SendMessageA(hwnd,CB_GETLBTEXT,(WPARAM)iItemId,(LPARAM)str);
152
153 #define CBGetCurSel(hwnd) \
154   SendMessageA(hwnd,CB_GETCURSEL,0,0);
155
156 #define CBSetCurSel(hwnd,pos) \
157   SendMessageA(hwnd,CB_SETCURSEL,(WPARAM)pos,0);
158
159 #define CBGetCount(hwnd) \
160     SendMessageA(hwnd,CB_GETCOUNT,0,0);
161 #define CBShowDropDown(hwnd,show) \
162   SendMessageA(hwnd,CB_SHOWDROPDOWN,(WPARAM)show,0);
163 #define CBSetItemHeight(hwnd,index,height) \
164   SendMessageA(hwnd,CB_SETITEMHEIGHT,(WPARAM)index,(LPARAM)height);
165
166
167 const char *FileOpenDlgInfosStr = "FileOpenDlgInfos"; /* windows property description string */
168 const char *LookInInfosStr = "LookInInfos"; /* LOOKIN combo box property */
169
170 /***********************************************************************
171  * Prototypes
172  */
173
174 /* Internal functions used by the dialog */
175 static LRESULT FILEDLG95_FillControls(HWND hwnd, WPARAM wParam, LPARAM lParam);
176 static LRESULT FILEDLG95_OnWMCommand(HWND hwnd, WPARAM wParam, LPARAM lParam);
177 static LRESULT FILEDLG95_OnWMGetIShellBrowser(HWND hwnd);
178        BOOL    FILEDLG95_OnOpen(HWND hwnd);
179 static LRESULT FILEDLG95_InitControls(HWND hwnd);
180 static void    FILEDLG95_Clean(HWND hwnd);
181
182 /* Functions used by the shell navigation */
183 static LRESULT FILEDLG95_SHELL_Init(HWND hwnd);
184 static BOOL    FILEDLG95_SHELL_UpFolder(HWND hwnd);
185 static BOOL    FILEDLG95_SHELL_ExecuteCommand(HWND hwnd, LPCSTR lpVerb);
186 static void    FILEDLG95_SHELL_Clean(HWND hwnd);
187 static BOOL    FILEDLG95_SHELL_BrowseToDesktop(HWND hwnd);
188
189 /* Functions used by the filetype combo box */
190 static HRESULT FILEDLG95_FILETYPE_Init(HWND hwnd);
191 static BOOL    FILEDLG95_FILETYPE_OnCommand(HWND hwnd, WORD wNotifyCode);
192 static int     FILEDLG95_FILETYPE_SearchExt(HWND hwnd,LPCWSTR lpstrExt);
193 static void    FILEDLG95_FILETYPE_Clean(HWND hwnd);
194
195 /* Functions used by the Look In combo box */
196 static HRESULT FILEDLG95_LOOKIN_Init(HWND hwndCombo);
197 static LRESULT FILEDLG95_LOOKIN_DrawItem(LPDRAWITEMSTRUCT pDIStruct);
198 static BOOL    FILEDLG95_LOOKIN_OnCommand(HWND hwnd, WORD wNotifyCode);
199 static int     FILEDLG95_LOOKIN_AddItem(HWND hwnd,LPITEMIDLIST pidl, int iInsertId);
200 static int     FILEDLG95_LOOKIN_SearchItem(HWND hwnd,WPARAM searchArg,int iSearchMethod);
201 static int     FILEDLG95_LOOKIN_InsertItemAfterParent(HWND hwnd,LPITEMIDLIST pidl);
202 static int     FILEDLG95_LOOKIN_RemoveMostExpandedItem(HWND hwnd);
203        int     FILEDLG95_LOOKIN_SelectItem(HWND hwnd,LPITEMIDLIST pidl);
204 static void    FILEDLG95_LOOKIN_Clean(HWND hwnd);
205
206 /* Miscellaneous tool functions */
207 HRESULT       GetName(LPSHELLFOLDER lpsf, LPITEMIDLIST pidl,DWORD dwFlags,LPSTR lpstrFileName);
208 HRESULT       GetFileName(HWND hwnd, LPITEMIDLIST pidl, LPSTR lpstrFileName);
209 IShellFolder* GetShellFolderFromPidl(LPITEMIDLIST pidlAbs);
210 LPITEMIDLIST  GetParentPidl(LPITEMIDLIST pidl);
211 LPITEMIDLIST  GetPidlFromName(IShellFolder *psf,LPWSTR lpcstrFileName);
212
213 /* Shell memory allocation */
214 static void *MemAlloc(UINT size);
215 static void MemFree(void *mem);
216
217 BOOL WINAPI GetFileName95(FileOpenDlgInfos *fodInfos);
218 INT_PTR CALLBACK FileOpenDlgProc95(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
219 HRESULT SendCustomDlgNotificationMessage(HWND hwndParentDlg, UINT uCode);
220 HRESULT FILEDLG95_HandleCustomDialogMessages(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
221 BOOL FILEDLG95_OnOpenMultipleFiles(HWND hwnd, LPWSTR lpstrFileList, UINT nFileCount, UINT sizeUsed);
222 static BOOL BrowseSelectedFolder(HWND hwnd);
223
224 /***********************************************************************
225  *      GetFileName95
226  *
227  * Creates an Open common dialog box that lets the user select
228  * the drive, directory, and the name of a file or set of files to open.
229  *
230  * IN  : The FileOpenDlgInfos structure associated with the dialog
231  * OUT : TRUE on success
232  *       FALSE on cancel, error, close or filename-does-not-fit-in-buffer.
233  */
234 BOOL WINAPI GetFileName95(FileOpenDlgInfos *fodInfos)
235 {
236
237     LRESULT lRes;
238     LPCVOID template;
239     HRSRC hRes;
240     HANDLE hDlgTmpl = 0;
241
242     /* test for missing functionality */
243     if (fodInfos->ofnInfos->Flags & UNIMPLEMENTED_FLAGS)
244     {
245       FIXME("Flags 0x%08lx not yet implemented\n",
246          fodInfos->ofnInfos->Flags & UNIMPLEMENTED_FLAGS);
247     }
248
249     /* Create the dialog from a template */
250
251     if(!(hRes = FindResourceA(COMMDLG_hInstance32,MAKEINTRESOURCEA(NEWFILEOPENORD),RT_DIALOGA)))
252     {
253         COMDLG32_SetCommDlgExtendedError(CDERR_FINDRESFAILURE);
254         return FALSE;
255     }
256     if (!(hDlgTmpl = LoadResource(COMMDLG_hInstance32, hRes )) ||
257         !(template = LockResource( hDlgTmpl )))
258     {
259         COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
260         return FALSE;
261     }
262
263     /* old style hook messages */
264     if (IsHooked(fodInfos))
265     {
266       fodInfos->HookMsg.fileokstring = RegisterWindowMessageA(FILEOKSTRINGA);
267       fodInfos->HookMsg.lbselchstring = RegisterWindowMessageA(LBSELCHSTRINGA);
268       fodInfos->HookMsg.helpmsgstring = RegisterWindowMessageA(HELPMSGSTRINGA);
269       fodInfos->HookMsg.sharevistring = RegisterWindowMessageA(SHAREVISTRINGA);
270     }
271
272     lRes = DialogBoxIndirectParamA(COMMDLG_hInstance32,
273                                   (LPDLGTEMPLATEA) template,
274                                   fodInfos->ofnInfos->hwndOwner,
275                                   FileOpenDlgProc95,
276                                   (LPARAM) fodInfos);
277
278     /* Unable to create the dialog */
279     if( lRes == -1)
280         return FALSE;
281
282     return lRes;
283 }
284
285 /***********************************************************************
286  *      GetFileDialog95A
287  *
288  * Call GetFileName95 with this structure and clean the memory.
289  *
290  * IN  : The OPENFILENAMEA initialisation structure passed to
291  *       GetOpenFileNameA win api function (see filedlg.c)
292  */
293 BOOL  WINAPI GetFileDialog95A(LPOPENFILENAMEA ofn,UINT iDlgType)
294 {
295   BOOL ret;
296   FileOpenDlgInfos fodInfos;
297   LPSTR lpstrSavDir = NULL;
298   LPWSTR title = NULL;
299   LPWSTR defext = NULL;
300   LPWSTR filter = NULL;
301   LPWSTR customfilter = NULL;
302
303   /* Initialize FileOpenDlgInfos structure */
304   ZeroMemory(&fodInfos, sizeof(FileOpenDlgInfos));
305
306   /* Pass in the original ofn */
307   fodInfos.ofnInfos = ofn;
308
309   /* save current directory */
310   if (ofn->Flags & OFN_NOCHANGEDIR)
311   {
312      lpstrSavDir = MemAlloc(MAX_PATH);
313      GetCurrentDirectoryA(MAX_PATH, lpstrSavDir);
314   }
315
316   fodInfos.unicode = FALSE;
317
318   /* convert all the input strings to unicode */
319   if(ofn->lpstrInitialDir)
320   {
321     DWORD len = MultiByteToWideChar( CP_ACP, 0, ofn->lpstrInitialDir, -1, NULL, 0 );
322     fodInfos.initdir = MemAlloc((len+1)*sizeof(WCHAR));
323     MultiByteToWideChar( CP_ACP, 0, ofn->lpstrInitialDir, -1, fodInfos.initdir, len);
324   }
325   else
326     fodInfos.initdir = NULL;
327
328   if(ofn->lpstrFile)
329   {
330     fodInfos.filename = MemAlloc(ofn->nMaxFile*sizeof(WCHAR));
331     MultiByteToWideChar( CP_ACP, 0, ofn->lpstrFile, -1, fodInfos.filename, ofn->nMaxFile);
332   }
333   else
334     fodInfos.filename = NULL;
335
336   if(ofn->lpstrDefExt)
337   {
338     DWORD len = MultiByteToWideChar( CP_ACP, 0, ofn->lpstrDefExt, -1, NULL, 0 );
339     defext = MemAlloc((len+1)*sizeof(WCHAR));
340     MultiByteToWideChar( CP_ACP, 0, ofn->lpstrDefExt, -1, defext, len);
341   }
342   fodInfos.defext = defext;
343
344   if(ofn->lpstrTitle)
345   {
346     DWORD len = MultiByteToWideChar( CP_ACP, 0, ofn->lpstrTitle, -1, NULL, 0 );
347     title = MemAlloc((len+1)*sizeof(WCHAR));
348     MultiByteToWideChar( CP_ACP, 0, ofn->lpstrTitle, -1, title, len);
349   }
350   fodInfos.title = title;
351
352   if (ofn->lpstrFilter)
353   {
354     LPCSTR s;
355     int n, len;
356
357     /* filter is a list...  title\0ext\0......\0\0 */
358     s = ofn->lpstrFilter;
359     while (*s) s = s+strlen(s)+1;
360     s++;
361     n = s - ofn->lpstrFilter;
362     len = MultiByteToWideChar( CP_ACP, 0, ofn->lpstrFilter, n, NULL, 0 );
363     filter = MemAlloc(len*sizeof(WCHAR));
364     MultiByteToWideChar( CP_ACP, 0, ofn->lpstrFilter, n, filter, len );
365   }
366   fodInfos.filter = filter;
367
368   /* convert lpstrCustomFilter */
369   if (ofn->lpstrCustomFilter)
370   {
371     LPCSTR s;
372     int n, len;
373
374     /* filter is a list...  title\0ext\0......\0\0 */
375     s = ofn->lpstrCustomFilter;
376     while (*s) s = s+strlen(s)+1;
377     s++;
378     n = s - ofn->lpstrCustomFilter;
379     len = MultiByteToWideChar( CP_ACP, 0, ofn->lpstrCustomFilter, n, NULL, 0 );
380     customfilter = MemAlloc(len*sizeof(WCHAR));
381     MultiByteToWideChar( CP_ACP, 0, ofn->lpstrCustomFilter, n, customfilter, len );
382   }
383   fodInfos.customfilter = customfilter;
384
385   /* Initialize the dialog property */
386   fodInfos.DlgInfos.dwDlgProp = 0;
387   fodInfos.DlgInfos.hwndCustomDlg = NULL;
388
389   switch(iDlgType)
390   {
391     case OPEN_DIALOG :
392       ret = GetFileName95(&fodInfos);
393       break;
394     case SAVE_DIALOG :
395       fodInfos.DlgInfos.dwDlgProp |= FODPROP_SAVEDLG;
396       ret = GetFileName95(&fodInfos);
397       break;
398     default :
399       ret = 0;
400   }
401
402   if (lpstrSavDir)
403   {
404       SetCurrentDirectoryA(lpstrSavDir);
405       MemFree(lpstrSavDir);
406   }
407
408   if(title)
409     MemFree(title);
410   if(defext)
411     MemFree(defext);
412   if(filter)
413     MemFree(filter);
414   if(customfilter)
415     MemFree(customfilter);
416   if(fodInfos.initdir)
417     MemFree(fodInfos.initdir);
418
419   if(fodInfos.filename)
420     MemFree(fodInfos.filename);
421
422   TRACE("selected file: %s\n",ofn->lpstrFile);
423
424   return ret;
425 }
426
427 /***********************************************************************
428  *      GetFileDialog95W
429  *
430  * Copy the OPENFILENAMEW structure in a FileOpenDlgInfos structure.
431  * Call GetFileName95 with this structure and clean the memory.
432  *
433  * FIXME: lpstrCustomFilter has to be converted back
434  *
435  */
436 BOOL  WINAPI GetFileDialog95W(LPOPENFILENAMEW ofn,UINT iDlgType)
437 {
438   BOOL ret;
439   FileOpenDlgInfos fodInfos;
440   LPSTR lpstrSavDir = NULL;
441
442   /* Initialize FileOpenDlgInfos structure */
443   ZeroMemory(&fodInfos, sizeof(FileOpenDlgInfos));
444
445   /*  Pass in the original ofn */
446   fodInfos.ofnInfos = (LPOPENFILENAMEA) ofn;
447
448   fodInfos.title = ofn->lpstrTitle;
449   fodInfos.defext = ofn->lpstrDefExt;
450   fodInfos.filter = ofn->lpstrFilter;
451   fodInfos.customfilter = ofn->lpstrCustomFilter;
452
453   /* convert string arguments, save others */
454   if(ofn->lpstrFile)
455   {
456     fodInfos.filename = MemAlloc(ofn->nMaxFile*sizeof(WCHAR));
457     strncpyW(fodInfos.filename,ofn->lpstrFile,ofn->nMaxFile);
458   }
459   else
460     fodInfos.filename = NULL;
461
462   if(ofn->lpstrInitialDir)
463   {
464     DWORD len = strlenW(ofn->lpstrInitialDir);
465     fodInfos.initdir = MemAlloc((len+1)*sizeof(WCHAR));
466     strcpyW(fodInfos.initdir,ofn->lpstrInitialDir);
467   }
468   else
469     fodInfos.initdir = NULL;
470
471   /* save current directory */
472   if (ofn->Flags & OFN_NOCHANGEDIR)
473   {
474      lpstrSavDir = MemAlloc(MAX_PATH);
475      GetCurrentDirectoryA(MAX_PATH, lpstrSavDir);
476   }
477
478   fodInfos.unicode = TRUE;
479
480   switch(iDlgType)
481   {
482   case OPEN_DIALOG :
483       ret = GetFileName95(&fodInfos);
484       break;
485   case SAVE_DIALOG :
486       fodInfos.DlgInfos.dwDlgProp |= FODPROP_SAVEDLG;
487       ret = GetFileName95(&fodInfos);
488       break;
489   default :
490       ret = 0;
491   }
492
493   if (lpstrSavDir)
494   {
495       SetCurrentDirectoryA(lpstrSavDir);
496       MemFree(lpstrSavDir);
497   }
498
499   /* restore saved IN arguments and convert OUT arguments back */
500   MemFree(fodInfos.filename);
501   MemFree(fodInfos.initdir);
502   return ret;
503 }
504
505 void ArrangeCtrlPositions( HWND hwndChildDlg, HWND hwndParentDlg)
506 {
507     HWND hwndChild,hwndStc32;
508     RECT rectParent, rectChild, rectCtrl, rectStc32, rectTemp;
509     POINT ptMoveCtl;
510     POINT ptParentClient;
511
512     TRACE("\n");
513
514     ptMoveCtl.x = ptMoveCtl.y = 0;
515     hwndStc32=GetDlgItem(hwndChildDlg,stc32);
516     GetClientRect(hwndParentDlg,&rectParent);
517     GetClientRect(hwndChildDlg,&rectChild);
518
519     if(hwndStc32)
520     {
521       GetWindowRect(hwndStc32,&rectStc32);
522       MapWindowPoints(0, hwndChildDlg,(LPPOINT)&rectStc32,2);
523       CopyRect(&rectTemp,&rectStc32);
524
525       SetRect(&rectStc32,rectStc32.left,rectStc32.top,rectStc32.left + (rectParent.right-rectParent.left),rectStc32.top+(rectParent.bottom-rectParent.top));
526       SetWindowPos(hwndStc32,0,rectStc32.left,rectStc32.top,rectStc32.right-rectStc32.left,rectStc32.bottom-rectStc32.top,SWP_NOMOVE|SWP_NOZORDER | SWP_NOACTIVATE);
527
528       ptParentClient.x = max((rectParent.right-rectParent.left),(rectChild.right-rectChild.left));
529       if(rectStc32.right < rectTemp.right)
530         ptMoveCtl.x = 0;
531       else
532         ptMoveCtl.x = (rectStc32.right - rectTemp.right);
533
534       ptParentClient.y = max((rectParent.bottom-rectParent.top),(rectChild.bottom-rectChild.top));
535       if(rectStc32.bottom < rectTemp.bottom)
536         ptMoveCtl.y = 0;
537       else
538         ptMoveCtl.y = (rectStc32.bottom - rectTemp.bottom);
539     }
540     else
541     {
542       if( (GetWindow(hwndChildDlg,GW_CHILD)) == NULL) return;
543
544       SetRectEmpty(&rectTemp);
545       ptParentClient.x = max((rectParent.right-rectParent.left),(rectChild.right-rectChild.left));
546       ptParentClient.y = (rectParent.bottom-rectParent.top) + (rectChild.bottom-rectChild.top);
547       ptMoveCtl.y = rectParent.bottom-rectParent.top;
548       ptMoveCtl.x=0;
549     }
550     SetRect(&rectParent,rectParent.left,rectParent.top,rectParent.left+ptParentClient.x,rectParent.top+ptParentClient.y);
551     AdjustWindowRectEx( &rectParent,GetWindowLongA(hwndParentDlg,GWL_STYLE),FALSE,GetWindowLongA(hwndParentDlg,GWL_EXSTYLE));
552
553     SetWindowPos(hwndChildDlg, 0, 0,0, ptParentClient.x + ptMoveCtl.x,ptParentClient.y + ptMoveCtl.y, SWP_NOZORDER );
554     SetWindowPos(hwndParentDlg, 0, rectParent.left,rectParent.top, (rectParent.right- rectParent.left) + ptMoveCtl.x,
555         (rectParent.bottom-rectParent.top) + ptMoveCtl.y,SWP_NOMOVE | SWP_NOZORDER);
556
557     hwndChild = GetWindow(hwndChildDlg,GW_CHILD);
558     if(hwndStc32)
559     {
560       GetWindowRect(hwndStc32,&rectStc32);
561       MapWindowPoints( 0, hwndChildDlg,(LPPOINT)&rectStc32,2);
562     }
563     else
564       SetRect(&rectStc32,0,0,0,0);
565
566     if (hwndChild )
567     {
568       do
569       {
570         if(hwndChild != hwndStc32)
571         {
572           if (GetWindowLongA( hwndChild, GWL_STYLE ) & WS_MAXIMIZE)
573                                 continue;
574           GetWindowRect(hwndChild,&rectCtrl);
575           MapWindowPoints( 0, hwndParentDlg,(LPPOINT)&rectCtrl,2);
576
577           /*
578             Check the initial position of the controls relative to the initial
579             position and size of stc32 (before it is expanded).
580           */
581           if (rectCtrl.left >= rectTemp.right && rectCtrl.top >= rectTemp.bottom)
582           {
583             rectCtrl.left += ptMoveCtl.x;
584             rectCtrl.top  += ptMoveCtl.y;
585           }
586           else if (rectCtrl.left >= rectTemp.right)
587           {
588             rectCtrl.left += ptMoveCtl.x;
589             rectCtrl.right += ptMoveCtl.x;
590           }
591           else if (rectCtrl.top >= rectTemp.bottom)
592           {
593             rectCtrl.top  += ptMoveCtl.y;
594            rectCtrl.bottom  += ptMoveCtl.y;
595           }
596
597           SetWindowPos( hwndChild, 0, rectCtrl.left, rectCtrl.top,
598                                 rectCtrl.right-rectCtrl.left,rectCtrl.bottom-rectCtrl.top,
599                                 SWP_NOSIZE | SWP_NOZORDER );
600         }
601       } while ((hwndChild=GetWindow( hwndChild, GW_HWNDNEXT )) != NULL);
602     }
603     hwndChild = GetWindow(hwndParentDlg,GW_CHILD);
604
605     if(hwndStc32)
606     {
607       GetWindowRect(hwndStc32,&rectStc32);
608       MapWindowPoints( 0, hwndChildDlg,(LPPOINT)&rectStc32,2);
609       ptMoveCtl.x = rectStc32.left - 0;
610       ptMoveCtl.y = rectStc32.top - 0;
611       if (hwndChild )
612       {
613         do
614         {
615           if(hwndChild != hwndChildDlg)
616           {
617             if (GetWindowLongA( hwndChild, GWL_STYLE ) & WS_MAXIMIZE)
618               continue;
619             GetWindowRect(hwndChild,&rectCtrl);
620             MapWindowPoints( 0, hwndParentDlg,(LPPOINT)&rectCtrl,2);
621
622             rectCtrl.left += ptMoveCtl.x;
623             rectCtrl.right += ptMoveCtl.x;
624             rectCtrl.top += ptMoveCtl.y;
625             rectCtrl.bottom += ptMoveCtl.y;
626
627             SetWindowPos( hwndChild, 0, rectCtrl.left, rectCtrl.top,
628                 rectCtrl.right-rectCtrl.left,rectCtrl.bottom-rectCtrl.top,
629                 SWP_NOSIZE |SWP_NOZORDER );
630           }
631         } while ((hwndChild=GetWindow( hwndChild, GW_HWNDNEXT )) != NULL);
632       }
633     }
634 }
635
636
637 INT_PTR CALLBACK FileOpenDlgProcUserTemplate(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
638 {
639     FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(GetParent(hwnd),FileOpenDlgInfosStr);
640
641 #if 0
642     TRACE("0x%04x\n", uMsg);
643 #endif
644
645     switch(uMsg)
646     {
647       case WM_INITDIALOG:
648       {
649         /* Hide caption since some program may leave it */
650         DWORD Style = GetWindowLongA(hwnd, GWL_STYLE);
651         if (Style & WS_CAPTION) SetWindowLongA(hwnd, GWL_STYLE, Style & (~WS_CAPTION));
652
653         fodInfos = (FileOpenDlgInfos *)lParam;
654         lParam = (LPARAM) fodInfos->ofnInfos;
655         ArrangeCtrlPositions(hwnd,GetParent(hwnd));
656
657         if(fodInfos && IsHooked(fodInfos))
658           return CallWindowProcA((WNDPROC)fodInfos->ofnInfos->lpfnHook,hwnd,uMsg,wParam,lParam);
659         return 0;
660       }
661     }
662
663     if(fodInfos && IsHooked(fodInfos))
664       return CallWindowProcA((WNDPROC)fodInfos->ofnInfos->lpfnHook,hwnd,uMsg,wParam,lParam);
665
666     return DefWindowProcA(hwnd,uMsg,wParam,lParam);
667 }
668
669 HWND CreateTemplateDialog(FileOpenDlgInfos *fodInfos, HWND hwnd)
670 {
671     LPCVOID template;
672     HRSRC hRes;
673     HANDLE hDlgTmpl = 0;
674     HWND hChildDlg = 0;
675
676     TRACE("\n");
677
678     /*
679      * If OFN_ENABLETEMPLATEHANDLE is specified, the OPENFILENAME
680      * structure's hInstance parameter is not a HINSTANCE, but
681      * instead a pointer to a template resource to use.
682      */
683     if (fodInfos->ofnInfos->Flags & OFN_ENABLETEMPLATE ||
684         fodInfos->ofnInfos->Flags & OFN_ENABLETEMPLATEHANDLE)
685     {
686       HINSTANCE hinst;
687
688       if (fodInfos->ofnInfos->Flags  & OFN_ENABLETEMPLATEHANDLE)
689       {
690         hinst = 0;
691         if( !(template = LockResource( fodInfos->ofnInfos->hInstance)))
692         {
693           COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
694           return NULL;
695         }
696       }
697       else
698       {
699         hinst = fodInfos->ofnInfos->hInstance;
700         if(fodInfos->unicode)
701         {
702             LPOPENFILENAMEW ofn = (LPOPENFILENAMEW) fodInfos->ofnInfos;
703             hRes = FindResourceW( hinst, ofn->lpTemplateName, RT_DIALOGW);
704         }
705         else
706         {
707             LPOPENFILENAMEA ofn = fodInfos->ofnInfos;
708             hRes = FindResourceA( hinst, ofn->lpTemplateName, RT_DIALOGA);
709         }
710         if (!hRes)
711         {
712           COMDLG32_SetCommDlgExtendedError(CDERR_FINDRESFAILURE);
713           return NULL;
714         }
715         if (!(hDlgTmpl = LoadResource( hinst, hRes )) ||
716             !(template = LockResource( hDlgTmpl )))
717         {
718           COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
719           return NULL;
720         }
721       }
722
723       hChildDlg= CreateDialogIndirectParamA(hinst, template,
724            hwnd, FileOpenDlgProcUserTemplate, (LPARAM)fodInfos);
725       if(hChildDlg)
726       {
727         ShowWindow(hChildDlg,SW_SHOW);
728         return hChildDlg;
729       }
730     }
731     else if( IsHooked(fodInfos))
732     {
733       RECT rectHwnd;
734       struct  {
735          DLGTEMPLATE tmplate;
736          WORD menu,class,title;
737          } temp;
738       GetClientRect(hwnd,&rectHwnd);
739       temp.tmplate.style = WS_CHILD | WS_CLIPSIBLINGS;
740       temp.tmplate.dwExtendedStyle = 0;
741       temp.tmplate.cdit = 0;
742       temp.tmplate.x = 0;
743       temp.tmplate.y = 0;
744       temp.tmplate.cx = rectHwnd.right-rectHwnd.left;
745       temp.tmplate.cy = rectHwnd.bottom-rectHwnd.top;
746       temp.menu = temp.class = temp.title = 0;
747       hChildDlg = CreateDialogIndirectParamA(fodInfos->ofnInfos->hInstance,&temp.tmplate,
748                   hwnd, FileOpenDlgProcUserTemplate, (LPARAM)fodInfos);
749       return hChildDlg;
750     }
751     return NULL;
752 }
753
754 /***********************************************************************
755 *          SendCustomDlgNotificationMessage
756 *
757 * Send CustomDialogNotification (CDN_FIRST -- CDN_LAST) message to the custom template dialog
758 */
759
760 HRESULT SendCustomDlgNotificationMessage(HWND hwndParentDlg, UINT uCode)
761 {
762     FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwndParentDlg,FileOpenDlgInfosStr);
763
764     TRACE("%p 0x%04x\n",hwndParentDlg, uCode);
765
766     if(!fodInfos) return 0;
767
768     if(fodInfos->unicode)
769       FIXME("sending OPENFILENAMEA structure. Hook is expecting OPENFILENAMEW!\n");
770
771     if(fodInfos->DlgInfos.hwndCustomDlg)
772     {
773         OFNOTIFYA ofnNotify;
774         HRESULT ret;
775         ofnNotify.hdr.hwndFrom=hwndParentDlg;
776         ofnNotify.hdr.idFrom=0;
777         ofnNotify.hdr.code = uCode;
778         ofnNotify.lpOFN = fodInfos->ofnInfos;
779         TRACE("CALL NOTIFY for %x\n", uCode);
780         ret = SendMessageA(fodInfos->DlgInfos.hwndCustomDlg,WM_NOTIFY,0,(LPARAM)&ofnNotify);
781         TRACE("RET NOTIFY\n");
782         return ret;
783     }
784     return TRUE;
785 }
786
787 HRESULT FILEDLG95_Handle_GetFilePath(HWND hwnd, DWORD size, LPSTR buffer)
788 {
789     UINT sizeUsed = 0, n, total;
790     LPWSTR lpstrFileList = NULL;
791     WCHAR lpstrCurrentDir[MAX_PATH];
792     FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
793
794     TRACE("CDM_GETFILEPATH:\n");
795
796     if ( ! (fodInfos->ofnInfos->Flags & OFN_EXPLORER ) )
797         return -1;
798
799     /* get path and filenames */
800     SHGetPathFromIDListW(fodInfos->ShellInfos.pidlAbsCurrent,lpstrCurrentDir);
801     n = FILEDLG95_FILENAME_GetFileNames(hwnd, &lpstrFileList, &sizeUsed);
802
803     TRACE("path >%s< filespec >%s< %d files\n",
804          debugstr_w(lpstrCurrentDir),debugstr_w(lpstrFileList),n);
805
806     total = WideCharToMultiByte(CP_ACP, 0, lpstrCurrentDir, -1, 
807                                 NULL, 0, NULL, NULL);
808     total += WideCharToMultiByte(CP_ACP, 0, lpstrFileList, sizeUsed, 
809                                 NULL, 0, NULL, NULL);
810
811     /* Prepend the current path */
812     n = WideCharToMultiByte(CP_ACP, 0, lpstrCurrentDir, -1, 
813                             buffer, size, NULL, NULL);
814
815     if(n<size)
816     {
817         /* 'n' includes trailing \0 */
818         buffer[n-1] = '\\';
819         WideCharToMultiByte(CP_ACP, 0, lpstrFileList, sizeUsed, 
820                             &buffer[n], size-n, NULL, NULL);
821     }
822     MemFree(lpstrFileList);
823
824     TRACE("returned -> %s\n",debugstr_a(buffer));
825
826     return total;
827 }
828
829 HRESULT FILEDLG95_Handle_GetFileSpec(HWND hwnd, DWORD size, LPSTR buffer)
830 {
831     UINT sizeUsed = 0;
832     LPWSTR lpstrFileList = NULL;
833
834     TRACE("CDM_GETSPEC:\n");
835
836     FILEDLG95_FILENAME_GetFileNames(hwnd, &lpstrFileList, &sizeUsed);
837     WideCharToMultiByte(CP_ACP, 0, lpstrFileList, sizeUsed, buffer, size, NULL, NULL);
838     MemFree(lpstrFileList);
839
840     return sizeUsed;
841 }
842
843 /***********************************************************************
844 *         FILEDLG95_HandleCustomDialogMessages
845 *
846 * Handle Custom Dialog Messages (CDM_FIRST -- CDM_LAST) messages
847 */
848 HRESULT FILEDLG95_HandleCustomDialogMessages(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
849 {
850     char lpstrPath[MAX_PATH];
851     FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
852     if(!fodInfos) return -1;
853
854     switch(uMsg)
855     {
856         case CDM_GETFILEPATH:
857             return FILEDLG95_Handle_GetFilePath(hwnd, (UINT)wParam, (LPSTR)lParam);
858
859         case CDM_GETFOLDERPATH:
860             TRACE("CDM_GETFOLDERPATH:\n");
861             SHGetPathFromIDListA(fodInfos->ShellInfos.pidlAbsCurrent,lpstrPath);
862             if ((LPSTR)lParam!=NULL)
863                 lstrcpynA((LPSTR)lParam,lpstrPath,(int)wParam);
864             return strlen(lpstrPath);
865
866         case CDM_GETSPEC:
867             return FILEDLG95_Handle_GetFileSpec(hwnd, (UINT)wParam, (LPSTR)lParam);
868
869         case CDM_SETCONTROLTEXT:
870             TRACE("CDM_SETCONTROLTEXT:\n");
871             if ( 0 != lParam )
872                 SetDlgItemTextA( hwnd, (UINT) wParam, (LPSTR) lParam );
873             return TRUE;
874
875         case CDM_HIDECONTROL:
876         case CDM_SETDEFEXT:
877             FIXME("CDM_HIDECONTROL,CDM_SETCONTROLTEXT,CDM_SETDEFEXT not implemented\n");
878             return -1;
879     }
880     return TRUE;
881 }
882
883 /***********************************************************************
884  *          FileOpenDlgProc95
885  *
886  * File open dialog procedure
887  */
888 INT_PTR CALLBACK FileOpenDlgProc95(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
889 {
890 #if 0
891   TRACE("0x%04x 0x%04x\n", hwnd, uMsg);
892 #endif
893
894   switch(uMsg)
895   {
896     case WM_INITDIALOG:
897       {
898          FileOpenDlgInfos * fodInfos = (FileOpenDlgInfos *)lParam;
899
900          /* Adds the FileOpenDlgInfos in the property list of the dialog
901             so it will be easily accessible through a GetPropA(...) */
902          SetPropA(hwnd, FileOpenDlgInfosStr, (HANDLE) fodInfos);
903
904          fodInfos->DlgInfos.hwndCustomDlg =
905            CreateTemplateDialog((FileOpenDlgInfos *)lParam, hwnd);
906
907          FILEDLG95_InitControls(hwnd);
908          SendCustomDlgNotificationMessage(hwnd,CDN_INITDONE);
909          FILEDLG95_FillControls(hwnd, wParam, lParam);
910          SendCustomDlgNotificationMessage(hwnd,CDN_FOLDERCHANGE);
911          SendCustomDlgNotificationMessage(hwnd,CDN_SELCHANGE);
912          SetWindowPos(fodInfos->DlgInfos.hwndCustomDlg, HWND_BOTTOM,
913                       0,0,0,0, SWP_NOMOVE|SWP_NOSIZE);
914          return 0;
915        }
916     case WM_COMMAND:
917       return FILEDLG95_OnWMCommand(hwnd, wParam, lParam);
918     case WM_DRAWITEM:
919       {
920         switch(((LPDRAWITEMSTRUCT)lParam)->CtlID)
921         {
922         case IDC_LOOKIN:
923           FILEDLG95_LOOKIN_DrawItem((LPDRAWITEMSTRUCT) lParam);
924           return TRUE;
925         }
926       }
927       return FALSE;
928
929     case WM_GETISHELLBROWSER:
930       return FILEDLG95_OnWMGetIShellBrowser(hwnd);
931
932     case WM_DESTROY:
933       RemovePropA(hwnd, FileOpenDlgInfosStr);
934       return FALSE;
935
936     case WM_NOTIFY:
937     {
938         LPNMHDR lpnmh = (LPNMHDR)lParam;
939         UINT stringId = -1;
940
941         /* set up the button tooltips strings */
942         if(TTN_GETDISPINFOA == lpnmh->code )
943         {
944             LPNMTTDISPINFOA lpdi = (LPNMTTDISPINFOA)lParam;
945             switch(lpnmh->idFrom )
946             {
947                 /* Up folder button */
948                 case FCIDM_TB_UPFOLDER:
949                     stringId = IDS_UPFOLDER;
950                     break;
951                 /* New folder button */
952                 case FCIDM_TB_NEWFOLDER:
953                     stringId = IDS_NEWFOLDER;
954                     break;
955                 /* List option button */
956                 case FCIDM_TB_SMALLICON:
957                     stringId = IDS_LISTVIEW;
958                     break;
959                 /* Details option button */
960                 case FCIDM_TB_REPORTVIEW:
961                     stringId = IDS_REPORTVIEW;
962                     break;
963                 /* Desktop button */
964                 case FCIDM_TB_DESKTOP:
965                     stringId = IDS_TODESKTOP;
966                     break;
967                 default:
968                     stringId = 0;
969             }
970             lpdi->hinst = COMMDLG_hInstance32;
971             lpdi->lpszText =  (LPSTR) stringId;
972         }
973         return FALSE;
974     }
975     default :
976       if(uMsg >= CDM_FIRST && uMsg <= CDM_LAST)
977         return FILEDLG95_HandleCustomDialogMessages(hwnd, uMsg, wParam, lParam);
978       return FALSE;
979   }
980 }
981
982 /***********************************************************************
983  *      FILEDLG95_InitControls
984  *
985  * WM_INITDIALOG message handler (before hook notification)
986  */
987 static LRESULT FILEDLG95_InitControls(HWND hwnd)
988 {
989   int win2000plus = 0;
990   int win98plus   = 0;
991   int handledPath = FALSE;
992   OSVERSIONINFOA osVi;
993   const WCHAR szwSlash[] = { '\\', 0 };
994   const WCHAR szwStar[] = { '*',0 };
995
996   TBBUTTON tbb[] =
997   {
998    {0,                 0,                   TBSTATE_ENABLED, TBSTYLE_SEP, {0, 0}, 0, 0 },
999    {VIEW_PARENTFOLDER, FCIDM_TB_UPFOLDER,   TBSTATE_ENABLED, TBSTYLE_BUTTON, {0, 0}, 0, 0 },
1000    {0,                 0,                   TBSTATE_ENABLED, TBSTYLE_SEP, {0, 0}, 0, 0 },
1001    {VIEW_NEWFOLDER+1,  FCIDM_TB_DESKTOP,    TBSTATE_ENABLED, TBSTYLE_BUTTON, {0, 0}, 0, 0 },
1002    {0,                 0,                   TBSTATE_ENABLED, TBSTYLE_SEP, {0, 0}, 0, 0 },
1003    {VIEW_NEWFOLDER,    FCIDM_TB_NEWFOLDER,  TBSTATE_ENABLED, TBSTYLE_BUTTON, {0, 0}, 0, 0 },
1004    {0,                 0,                   TBSTATE_ENABLED, TBSTYLE_SEP, {0, 0}, 0, 0 },
1005    {VIEW_LIST,         FCIDM_TB_SMALLICON,  TBSTATE_ENABLED, TBSTYLE_BUTTON, {0, 0}, 0, 0 },
1006    {VIEW_DETAILS,      FCIDM_TB_REPORTVIEW, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0, 0}, 0, 0 },
1007   };
1008   TBADDBITMAP tba[2];
1009   RECT rectTB;
1010   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
1011
1012   tba[0].hInst = HINST_COMMCTRL;
1013   tba[0].nID   = IDB_VIEW_SMALL_COLOR;
1014   tba[1].hInst = COMDLG32_hInstance;
1015   tba[1].nID   = 800;
1016
1017   TRACE("%p\n", fodInfos);
1018
1019   /* Get windows version emulating */
1020   osVi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
1021   GetVersionExA(&osVi);
1022   if (osVi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1023     win98plus   = ((osVi.dwMajorVersion > 4) || ((osVi.dwMajorVersion == 4) && (osVi.dwMinorVersion > 0)));
1024   } else if (osVi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1025     win2000plus = (osVi.dwMajorVersion > 4);
1026     if (win2000plus) win98plus = TRUE;
1027   }
1028   TRACE("Running on 2000+ %d, 98+ %d\n", win2000plus, win98plus);
1029
1030   /* Get the hwnd of the controls */
1031   fodInfos->DlgInfos.hwndFileName = GetDlgItem(hwnd,IDC_FILENAME);
1032   fodInfos->DlgInfos.hwndFileTypeCB = GetDlgItem(hwnd,IDC_FILETYPE);
1033   fodInfos->DlgInfos.hwndLookInCB = GetDlgItem(hwnd,IDC_LOOKIN);
1034
1035   /* construct the toolbar */
1036   GetWindowRect(GetDlgItem(hwnd,IDC_TOOLBARSTATIC),&rectTB);
1037   MapWindowPoints( 0, hwnd,(LPPOINT)&rectTB,2);
1038
1039   fodInfos->DlgInfos.hwndTB = CreateWindowExA(0, TOOLBARCLASSNAMEA, NULL,
1040         WS_CHILD | WS_GROUP | TBSTYLE_TOOLTIPS | CCS_NODIVIDER | CCS_NORESIZE,
1041         0, 0, 150, 26, hwnd, (HMENU) IDC_TOOLBAR, COMMDLG_hInstance32, NULL);
1042
1043   SetWindowPos(fodInfos->DlgInfos.hwndTB, 0,
1044         rectTB.left,rectTB.top, rectTB.right-rectTB.left, rectTB.bottom-rectTB.top,
1045         SWP_SHOWWINDOW | SWP_NOACTIVATE | SWP_NOZORDER );
1046
1047   SendMessageA(fodInfos->DlgInfos.hwndTB, TB_BUTTONSTRUCTSIZE, (WPARAM) sizeof(TBBUTTON), 0);
1048
1049 /* FIXME: use TB_LOADIMAGES when implemented */
1050 /*  SendMessageA(fodInfos->DlgInfos.hwndTB, TB_LOADIMAGES, (WPARAM) IDB_VIEW_SMALL_COLOR, HINST_COMMCTRL);*/
1051   SendMessageA(fodInfos->DlgInfos.hwndTB, TB_ADDBITMAP, (WPARAM) 12, (LPARAM) &tba[0]);
1052   SendMessageA(fodInfos->DlgInfos.hwndTB, TB_ADDBITMAP, (WPARAM) 1, (LPARAM) &tba[1]);
1053
1054   SendMessageA(fodInfos->DlgInfos.hwndTB, TB_ADDBUTTONSA, (WPARAM) 9,(LPARAM) &tbb);
1055   SendMessageA(fodInfos->DlgInfos.hwndTB, TB_AUTOSIZE, 0, 0);
1056
1057   /* Set the window text with the text specified in the OPENFILENAME structure */
1058   if(fodInfos->title)
1059   {
1060       SetWindowTextW(hwnd,fodInfos->title);
1061   }
1062   else if (fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG)
1063   {
1064       SetWindowTextA(hwnd,"Save");
1065   }
1066
1067   /* Initialise the file name edit control */
1068   handledPath = FALSE;
1069   TRACE("Before manipilation, file = %s, dir = %s\n", debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));
1070
1071   if(fodInfos->filename)
1072   {
1073       /* 1. If win2000 or higher and filename contains a path, use it
1074          in preference over the lpstrInitialDir                       */
1075       if (win2000plus && *fodInfos->filename && strpbrkW(fodInfos->filename, szwSlash)) {
1076          WCHAR tmpBuf[MAX_PATH];
1077          WCHAR *nameBit;
1078          DWORD result;
1079
1080          result = GetFullPathNameW(fodInfos->filename, MAX_PATH, tmpBuf, &nameBit);
1081          if (result) {
1082
1083             /* nameBit is always shorter than the original filename */
1084             strcpyW(fodInfos->filename,nameBit);
1085
1086             *nameBit = 0x00;
1087             if (fodInfos->initdir == NULL)
1088                 MemFree(fodInfos->initdir);
1089             fodInfos->initdir = MemAlloc((strlenW(tmpBuf) + 1)*sizeof(WCHAR));
1090             strcpyW(fodInfos->initdir, tmpBuf);
1091             handledPath = TRUE;
1092             TRACE("Value in Filename includes path, overriding InitialDir: %s, %s\n",
1093                     debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));
1094          }
1095          SetDlgItemTextW(hwnd, IDC_FILENAME, fodInfos->filename);
1096
1097       } else {
1098          SetDlgItemTextW(hwnd, IDC_FILENAME, fodInfos->filename);
1099       }
1100   }
1101
1102   /* 2. (All platforms) If initdir is not null, then use it */
1103   if ((handledPath == FALSE) && (fodInfos->initdir!=NULL) &&
1104                                 (*fodInfos->initdir!=0x00))
1105   {
1106       /* Work out the proper path as supplied one might be relative          */
1107       /* (Here because supplying '.' as dir browses to My Computer)          */
1108       if (handledPath==FALSE) {
1109           WCHAR tmpBuf[MAX_PATH];
1110           WCHAR tmpBuf2[MAX_PATH];
1111           WCHAR *nameBit;
1112           DWORD result;
1113
1114           strcpyW(tmpBuf, fodInfos->initdir);
1115           if (tmpBuf[strlenW(tmpBuf)-1] != '\\') {
1116              strcatW(tmpBuf, szwSlash);
1117           }
1118           strcatW(tmpBuf, szwStar);
1119           result = GetFullPathNameW(tmpBuf, MAX_PATH, tmpBuf2, &nameBit);
1120           if (result) {
1121              *nameBit = 0x00;
1122              if (fodInfos->initdir)
1123                 MemFree(fodInfos->initdir);
1124              fodInfos->initdir = MemAlloc((strlenW(tmpBuf2) + 1)*sizeof(WCHAR));
1125              strcpyW(fodInfos->initdir, tmpBuf2);
1126              handledPath = TRUE;
1127              TRACE("Value in InitDir changed to %s\n", debugstr_w(fodInfos->initdir));
1128           }
1129       }
1130   }
1131
1132   if ((handledPath == FALSE) && ((fodInfos->initdir==NULL) ||
1133                                  (*fodInfos->initdir==0x00)))
1134   {
1135       /* 3. All except w2k+: if filename contains a path use it */
1136       if (!win2000plus && fodInfos->filename &&
1137           *fodInfos->filename &&
1138           strpbrkW(fodInfos->filename, szwSlash)) {
1139          WCHAR tmpBuf[MAX_PATH];
1140          WCHAR *nameBit;
1141          DWORD result;
1142
1143          result = GetFullPathNameW(fodInfos->filename, MAX_PATH,
1144                                   tmpBuf, &nameBit);
1145          if (result) {
1146             int len;
1147
1148             /* nameBit is always shorter than the original filename */
1149             strcpyW(fodInfos->filename, nameBit);
1150             *nameBit = 0x00;
1151
1152             len = strlenW(tmpBuf);
1153             if(fodInfos->initdir)
1154                MemFree(fodInfos->initdir);
1155             fodInfos->initdir = MemAlloc((len+1)*sizeof(WCHAR));
1156             strcpyW(fodInfos->initdir, tmpBuf);
1157
1158             handledPath = TRUE;
1159             TRACE("Value in Filename includes path, overriding initdir: %s, %s\n",
1160                  debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));
1161          }
1162          SetDlgItemTextW(hwnd, IDC_FILENAME, fodInfos->filename);
1163       }
1164
1165       /* 4. win98+ and win2000+ if any files of specified filter types in
1166             current directory, use it                                      */
1167       if ( win98plus && handledPath == FALSE &&
1168            fodInfos->filter && *fodInfos->filter) {
1169
1170          BOOL   searchMore = TRUE;
1171          LPCWSTR lpstrPos = fodInfos->filter;
1172          WIN32_FIND_DATAW FindFileData;
1173          HANDLE hFind;
1174
1175          while (searchMore)
1176          {
1177            /* filter is a list...  title\0ext\0......\0\0 */
1178
1179            /* Skip the title */
1180            if(! *lpstrPos) break;       /* end */
1181            lpstrPos += strlenW(lpstrPos) + 1;
1182
1183            /* See if any files exist in the current dir with this extension */
1184            if(! *lpstrPos) break;       /* end */
1185
1186            hFind = FindFirstFileW(lpstrPos, &FindFileData);
1187
1188            if (hFind == INVALID_HANDLE_VALUE) {
1189                /* None found - continue search */
1190                lpstrPos += strlenW(lpstrPos) + 1;
1191
1192            } else {
1193                searchMore = FALSE;
1194
1195                if(fodInfos->initdir)
1196                   MemFree(fodInfos->initdir);
1197                fodInfos->initdir = MemAlloc(MAX_PATH*sizeof(WCHAR));
1198                GetCurrentDirectoryW(MAX_PATH, fodInfos->initdir);
1199
1200                handledPath = TRUE;
1201                TRACE("No initial dir specified, but files of type %s found in current, so using it\n",
1202                  debugstr_w(lpstrPos));
1203                break;
1204            }
1205          }
1206       }
1207
1208       /* 5. Win2000+: FIXME: Next, Recently used? Not sure how windows does this */
1209
1210       /* 6. Win98+ and 2000+: Use personal files dir, others use current dir */
1211       if (handledPath == FALSE && (win2000plus || win98plus)) {
1212           fodInfos->initdir = MemAlloc(MAX_PATH*sizeof(WCHAR));
1213
1214           if(FAILED(COMDLG32_SHGetFolderPathW(hwnd, CSIDL_PERSONAL, 0, 0, fodInfos->initdir)))
1215           {
1216             if(FAILED(COMDLG32_SHGetFolderPathW(hwnd, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, 0, 0, fodInfos->initdir)))
1217             {
1218                 /* last fallback */
1219                 GetCurrentDirectoryW(MAX_PATH, fodInfos->initdir);
1220                 TRACE("No personal or desktop dir, using cwd as failsafe: %s\n", debugstr_w(fodInfos->initdir));
1221             } else {
1222                 TRACE("No personal dir, using desktop instead: %s\n", debugstr_w(fodInfos->initdir));
1223             }
1224           } else {
1225             TRACE("No initial dir specified, using personal files dir of %s\n", debugstr_w(fodInfos->initdir));
1226           }
1227           handledPath = TRUE;
1228       } else if (handledPath==FALSE) {
1229           fodInfos->initdir = MemAlloc(MAX_PATH*sizeof(WCHAR));
1230           GetCurrentDirectoryW(MAX_PATH, fodInfos->initdir);
1231           handledPath = TRUE;
1232           TRACE("No initial dir specified, using current dir of %s\n", debugstr_w(fodInfos->initdir));
1233       }
1234   }
1235   TRACE("After manipilation, file = %s, dir = %s\n", debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));
1236
1237   /* Must the open as read only check box be checked ?*/
1238   if(fodInfos->ofnInfos->Flags & OFN_READONLY)
1239   {
1240     SendDlgItemMessageA(hwnd,IDC_OPENREADONLY,BM_SETCHECK,(WPARAM)TRUE,0);
1241   }
1242
1243   /* Must the open as read only check box be hid ?*/
1244   if(fodInfos->ofnInfos->Flags & OFN_HIDEREADONLY)
1245   {
1246     ShowWindow(GetDlgItem(hwnd,IDC_OPENREADONLY),SW_HIDE);
1247   }
1248
1249   /* Must the help button be hid ?*/
1250   if (!(fodInfos->ofnInfos->Flags & OFN_SHOWHELP))
1251   {
1252     ShowWindow(GetDlgItem(hwnd, pshHelp), SW_HIDE);
1253   }
1254
1255   /* Resize the height, if open as read only checkbox ad help button
1256      are hidden and we are not using a custom template */
1257   if ( (fodInfos->ofnInfos->Flags & OFN_HIDEREADONLY) &&
1258        (!(fodInfos->ofnInfos->Flags &
1259          (OFN_SHOWHELP|OFN_ENABLETEMPLATE|OFN_ENABLETEMPLATEHANDLE))))
1260   {
1261     RECT rectDlg, rectHelp, rectCancel;
1262     GetWindowRect(hwnd, &rectDlg);
1263     GetWindowRect(GetDlgItem(hwnd, pshHelp), &rectHelp);
1264     GetWindowRect(GetDlgItem(hwnd, IDCANCEL), &rectCancel);
1265     /* subtract the height of the help button plus the space between
1266        the help button and the cancel button to the height of the dialog */
1267     SetWindowPos(hwnd, 0, 0, 0, rectDlg.right-rectDlg.left,
1268                  (rectDlg.bottom-rectDlg.top) - (rectHelp.bottom - rectCancel.bottom),
1269                  SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);
1270   }
1271
1272   /* change Open to Save FIXME: use resources */
1273   if (fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG)
1274   {
1275       SetDlgItemTextA(hwnd,IDOK,"&Save");
1276       SetDlgItemTextA(hwnd,IDC_LOOKINSTATIC,"Save &in");
1277   }
1278   return 0;
1279 }
1280
1281 /***********************************************************************
1282  *      FILEDLG95_FillControls
1283  *
1284  * WM_INITDIALOG message handler (after hook notification)
1285  */
1286 static LRESULT FILEDLG95_FillControls(HWND hwnd, WPARAM wParam, LPARAM lParam)
1287 {
1288   LPITEMIDLIST pidlItemId = NULL;
1289
1290   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) lParam;
1291
1292   TRACE("dir=%s file=%s\n",
1293   debugstr_w(fodInfos->initdir), debugstr_w(fodInfos->filename));
1294
1295   /* Get the initial directory pidl */
1296
1297   if(!(pidlItemId = GetPidlFromName(fodInfos->Shell.FOIShellFolder,fodInfos->initdir)))
1298   {
1299     WCHAR path[MAX_PATH];
1300
1301     GetCurrentDirectoryW(MAX_PATH,path);
1302     pidlItemId = GetPidlFromName(fodInfos->Shell.FOIShellFolder, path);
1303   }
1304
1305   /* Initialise shell objects */
1306   FILEDLG95_SHELL_Init(hwnd);
1307
1308   /* Initialize the Look In combo box */
1309   FILEDLG95_LOOKIN_Init(fodInfos->DlgInfos.hwndLookInCB);
1310
1311   /* Initialize the filter combo box */
1312   FILEDLG95_FILETYPE_Init(hwnd);
1313
1314   /* Browse to the initial directory */
1315   IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser,pidlItemId, SBSP_ABSOLUTE);
1316
1317   /* Free pidlItem memory */
1318   COMDLG32_SHFree(pidlItemId);
1319
1320   return TRUE;
1321 }
1322 /***********************************************************************
1323  *      FILEDLG95_Clean
1324  *
1325  * Regroups all the cleaning functions of the filedlg
1326  */
1327 void FILEDLG95_Clean(HWND hwnd)
1328 {
1329       FILEDLG95_FILETYPE_Clean(hwnd);
1330       FILEDLG95_LOOKIN_Clean(hwnd);
1331       FILEDLG95_SHELL_Clean(hwnd);
1332 }
1333 /***********************************************************************
1334  *      FILEDLG95_OnWMCommand
1335  *
1336  * WM_COMMAND message handler
1337  */
1338 static LRESULT FILEDLG95_OnWMCommand(HWND hwnd, WPARAM wParam, LPARAM lParam)
1339 {
1340   WORD wNotifyCode = HIWORD(wParam); /* notification code */
1341   WORD wID = LOWORD(wParam);         /* item, control, or accelerator identifier */
1342   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
1343
1344   switch(wID)
1345   {
1346     /* OK button */
1347   case IDOK:
1348     FILEDLG95_OnOpen(hwnd);
1349     break;
1350     /* Cancel button */
1351   case IDCANCEL:
1352     FILEDLG95_Clean(hwnd);
1353     EndDialog(hwnd, FALSE);
1354     break;
1355     /* Filetype combo box */
1356   case IDC_FILETYPE:
1357     FILEDLG95_FILETYPE_OnCommand(hwnd,wNotifyCode);
1358     break;
1359     /* LookIn combo box */
1360   case IDC_LOOKIN:
1361     FILEDLG95_LOOKIN_OnCommand(hwnd,wNotifyCode);
1362     break;
1363
1364   /* --- toolbar --- */
1365     /* Up folder button */
1366   case FCIDM_TB_UPFOLDER:
1367     FILEDLG95_SHELL_UpFolder(hwnd);
1368     break;
1369     /* New folder button */
1370   case FCIDM_TB_NEWFOLDER:
1371     FILEDLG95_SHELL_ExecuteCommand(hwnd,CMDSTR_NEWFOLDER);
1372     break;
1373     /* List option button */
1374   case FCIDM_TB_SMALLICON:
1375     FILEDLG95_SHELL_ExecuteCommand(hwnd,CMDSTR_VIEWLIST);
1376     break;
1377     /* Details option button */
1378   case FCIDM_TB_REPORTVIEW:
1379     FILEDLG95_SHELL_ExecuteCommand(hwnd,CMDSTR_VIEWDETAILS);
1380     break;
1381     /* Details option button */
1382   case FCIDM_TB_DESKTOP:
1383     FILEDLG95_SHELL_BrowseToDesktop(hwnd);
1384     break;
1385
1386   case IDC_FILENAME:
1387     break;
1388
1389   }
1390   /* Do not use the listview selection anymore */
1391   fodInfos->DlgInfos.dwDlgProp &= ~FODPROP_USEVIEW;
1392   return 0;
1393 }
1394
1395 /***********************************************************************
1396  *      FILEDLG95_OnWMGetIShellBrowser
1397  *
1398  * WM_GETISHELLBROWSER message handler
1399  */
1400 static LRESULT FILEDLG95_OnWMGetIShellBrowser(HWND hwnd)
1401 {
1402
1403   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
1404
1405   TRACE("\n");
1406
1407   SetWindowLongA(hwnd,DWL_MSGRESULT,(LONG)fodInfos->Shell.FOIShellBrowser);
1408
1409   return TRUE;
1410 }
1411
1412
1413 /***********************************************************************
1414  *      FILEDLG95_SendFileOK
1415  *
1416  * Sends the CDN_FILEOK notification if required
1417  *
1418  * RETURNS
1419  *  TRUE if the dialog should close
1420  *  FALSE if the dialog should not be closed
1421  */
1422 static BOOL FILEDLG95_SendFileOK( HWND hwnd, FileOpenDlgInfos *fodInfos )
1423 {
1424     /* ask the hook if we can close */
1425     if(IsHooked(fodInfos))
1426     {
1427         TRACE("---\n");
1428         /* First send CDN_FILEOK as MSDN doc says */
1429         SendCustomDlgNotificationMessage(hwnd,CDN_FILEOK);
1430
1431         /* fodInfos->ofnInfos points to an ASCII or UNICODE structure as appropriate */
1432         CallWindowProcA((WNDPROC)fodInfos->ofnInfos->lpfnHook,
1433                             fodInfos->DlgInfos.hwndCustomDlg,
1434                             fodInfos->HookMsg.fileokstring, 0, (LPARAM)fodInfos->ofnInfos);
1435         if (GetWindowLongA(fodInfos->DlgInfos.hwndCustomDlg, DWL_MSGRESULT))
1436         {
1437             TRACE("canceled\n");
1438             return FALSE;
1439         }
1440     }
1441     return TRUE;
1442 }
1443
1444 /***********************************************************************
1445  *      FILEDLG95_OnOpenMultipleFiles
1446  *
1447  * Handles the opening of multiple files.
1448  *
1449  * FIXME
1450  *  check destination buffer size
1451  */
1452 BOOL FILEDLG95_OnOpenMultipleFiles(HWND hwnd, LPWSTR lpstrFileList, UINT nFileCount, UINT sizeUsed)
1453 {
1454   WCHAR   lpstrPathSpec[MAX_PATH] = {0};
1455   UINT   nCount, nSizePath;
1456   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
1457
1458   TRACE("\n");
1459
1460   if(fodInfos->unicode)
1461   {
1462      LPOPENFILENAMEW ofn = (LPOPENFILENAMEW) fodInfos->ofnInfos;
1463      ofn->lpstrFile[0] = '\0';
1464   }
1465   else
1466   {
1467      LPOPENFILENAMEA ofn = fodInfos->ofnInfos;
1468      ofn->lpstrFile[0] = '\0';
1469   }
1470
1471   SHGetPathFromIDListW( fodInfos->ShellInfos.pidlAbsCurrent, lpstrPathSpec );
1472
1473   if ( !(fodInfos->ofnInfos->Flags & OFN_NOVALIDATE) &&
1474       ( fodInfos->ofnInfos->Flags & OFN_FILEMUSTEXIST) &&
1475        ! ( fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG ) )
1476   {
1477     LPWSTR lpstrTemp = lpstrFileList;
1478
1479     for ( nCount = 0; nCount < nFileCount; nCount++ )
1480     {
1481       LPITEMIDLIST pidl;
1482
1483       pidl = GetPidlFromName(fodInfos->Shell.FOIShellFolder, lpstrTemp);
1484       if (!pidl)
1485       {
1486         WCHAR lpstrNotFound[100];
1487         WCHAR lpstrMsg[100];
1488         WCHAR tmp[400];
1489         WCHAR nl[] = {'\n',0};
1490
1491         LoadStringW(COMMDLG_hInstance32, IDS_FILENOTFOUND, lpstrNotFound, 100);
1492         LoadStringW(COMMDLG_hInstance32, IDS_VERIFYFILE, lpstrMsg, 100);
1493
1494         strcpyW(tmp, lpstrTemp);
1495         strcatW(tmp, nl);
1496         strcatW(tmp, lpstrNotFound);
1497         strcatW(tmp, nl);
1498         strcatW(tmp, lpstrMsg);
1499
1500         MessageBoxW(hwnd, tmp, fodInfos->title, MB_OK | MB_ICONEXCLAMATION);
1501         return FALSE;
1502       }
1503
1504       /* move to the next file in the list of files */
1505       lpstrTemp += strlenW(lpstrTemp) + 1;
1506       COMDLG32_SHFree(pidl);
1507     }
1508   }
1509
1510   nSizePath = strlenW(lpstrPathSpec) + 1;
1511   if ( !(fodInfos->ofnInfos->Flags & OFN_EXPLORER) )
1512   {
1513     /* For "oldstyle" dialog the components have to
1514        be spearated by blanks (not '\0'!) and short
1515        filenames have to be used! */
1516     FIXME("Components have to be separated by blanks");
1517   }
1518   if(fodInfos->unicode)
1519   {
1520     LPOPENFILENAMEW ofn = (LPOPENFILENAMEW) fodInfos->ofnInfos;
1521     strcpyW( ofn->lpstrFile, lpstrPathSpec);
1522     memcpy( ofn->lpstrFile + nSizePath, lpstrFileList, sizeUsed*sizeof(WCHAR) );
1523   }
1524   else
1525   {
1526     LPOPENFILENAMEA ofn = fodInfos->ofnInfos;
1527
1528     if (ofn->lpstrFile != NULL)
1529     {
1530       WideCharToMultiByte(CP_ACP, 0, lpstrPathSpec, -1,
1531                           ofn->lpstrFile, ofn->nMaxFile, NULL, NULL);
1532       if (ofn->nMaxFile > nSizePath)
1533       {
1534         WideCharToMultiByte(CP_ACP, 0, lpstrFileList, sizeUsed,
1535                             ofn->lpstrFile + nSizePath,
1536                             ofn->nMaxFile - nSizePath, NULL, NULL);
1537       }
1538     }
1539   }
1540
1541   fodInfos->ofnInfos->nFileOffset = nSizePath + 1;
1542   fodInfos->ofnInfos->nFileExtension = 0;
1543
1544   if ( !FILEDLG95_SendFileOK(hwnd, fodInfos) )
1545     return FALSE;
1546
1547   /* clean and exit */
1548   FILEDLG95_Clean(hwnd);
1549   return EndDialog(hwnd,TRUE);
1550 }
1551
1552 /***********************************************************************
1553  *      FILEDLG95_OnOpen
1554  *
1555  * Ok button WM_COMMAND message handler
1556  *
1557  * If the function succeeds, the return value is nonzero.
1558  */
1559 #define ONOPEN_BROWSE 1
1560 #define ONOPEN_OPEN   2
1561 #define ONOPEN_SEARCH 3
1562 static void FILEDLG95_OnOpenMessage(HWND hwnd, int idCaption, int idText)
1563 {
1564   char strMsgTitle[MAX_PATH];
1565   char strMsgText [MAX_PATH];
1566   if (idCaption)
1567     LoadStringA(COMDLG32_hInstance, idCaption, strMsgTitle, sizeof(strMsgTitle));
1568   else
1569     strMsgTitle[0] = '\0';
1570   LoadStringA(COMDLG32_hInstance, idText, strMsgText, sizeof(strMsgText));
1571   MessageBoxA(hwnd,strMsgText, strMsgTitle, MB_OK | MB_ICONHAND);
1572 }
1573
1574 BOOL FILEDLG95_OnOpen(HWND hwnd)
1575 {
1576   LPWSTR lpstrFileList;
1577   UINT nFileCount = 0;
1578   UINT sizeUsed = 0;
1579   BOOL ret = TRUE;
1580   WCHAR lpstrPathAndFile[MAX_PATH];
1581   WCHAR lpstrTemp[MAX_PATH];
1582   LPSHELLFOLDER lpsf = NULL;
1583   int nOpenAction;
1584   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
1585
1586   TRACE("hwnd=%p\n", hwnd);
1587
1588   /* get the files from the edit control */
1589   nFileCount = FILEDLG95_FILENAME_GetFileNames(hwnd, &lpstrFileList, &sizeUsed);
1590
1591   /* try if the user selected a folder in the shellview */
1592   if(nFileCount == 0)
1593   {
1594       BrowseSelectedFolder(hwnd);
1595       return FALSE;
1596   }
1597
1598   if(nFileCount > 1)
1599   {
1600       ret = FILEDLG95_OnOpenMultipleFiles(hwnd, lpstrFileList, nFileCount, sizeUsed);
1601       goto ret;
1602   }
1603
1604   TRACE("count=%u len=%u file=%s\n", nFileCount, sizeUsed, debugstr_w(lpstrFileList));
1605
1606 /*
1607   Step 1:  Build a complete path name from the current folder and
1608   the filename or path in the edit box.
1609   Special cases:
1610   - the path in the edit box is a root path
1611     (with or without drive letter)
1612   - the edit box contains ".." (or a path with ".." in it)
1613 */
1614
1615   /* Get the current directory name */
1616   if (!SHGetPathFromIDListW(fodInfos->ShellInfos.pidlAbsCurrent, lpstrPathAndFile))
1617   {
1618     /* we are in a special folder, default to desktop */
1619     if(FAILED(COMDLG32_SHGetFolderPathW(hwnd, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, 0, 0, lpstrPathAndFile)))
1620     {
1621       /* last fallback */
1622       GetCurrentDirectoryW(MAX_PATH, lpstrPathAndFile);
1623     }
1624   }
1625   PathAddBackslashW(lpstrPathAndFile);
1626
1627   TRACE("current directory=%s\n", debugstr_w(lpstrPathAndFile));
1628
1629   /* if the user specifyed a fully qualified path use it */
1630   if(PathIsRelativeW(lpstrFileList))
1631   {
1632     strcatW(lpstrPathAndFile, lpstrFileList);
1633   }
1634   else
1635   {
1636     /* does the path have a drive letter? */
1637     if (PathGetDriveNumberW(lpstrFileList) == -1)
1638       strcpyW(lpstrPathAndFile+2, lpstrFileList);
1639     else
1640       strcpyW(lpstrPathAndFile, lpstrFileList);
1641   }
1642
1643   /* resolve "." and ".." */
1644   PathCanonicalizeW(lpstrTemp, lpstrPathAndFile );
1645   strcpyW(lpstrPathAndFile, lpstrTemp);
1646   TRACE("canon=%s\n", debugstr_w(lpstrPathAndFile));
1647
1648   MemFree(lpstrFileList);
1649
1650 /*
1651   Step 2: here we have a cleaned up path
1652
1653   We have to parse the path step by step to see if we have to browse
1654   to a folder if the path points to a directory or the last
1655   valid element is a directory.
1656
1657   valid variables:
1658     lpstrPathAndFile: cleaned up path
1659  */
1660
1661   nOpenAction = ONOPEN_BROWSE;
1662
1663   /* dont apply any checks with OFN_NOVALIDATE */
1664   {
1665     LPWSTR lpszTemp, lpszTemp1;
1666     LPITEMIDLIST pidl = NULL;
1667     WCHAR szwInvalid[] = { '/',':','<','>','|', 0};
1668
1669     /* check for invalid chars */
1670     if((strpbrkW(lpstrPathAndFile+3, szwInvalid) != NULL) && !(fodInfos->ofnInfos->Flags & OFN_NOVALIDATE))
1671     {
1672       FILEDLG95_OnOpenMessage(hwnd, IDS_INVALID_FILENAME_TITLE, IDS_INVALID_FILENAME);
1673       ret = FALSE;
1674       goto ret;
1675     }
1676
1677     if (FAILED (SHGetDesktopFolder(&lpsf))) return FALSE;
1678
1679     lpszTemp1 = lpszTemp = lpstrPathAndFile;
1680     while (lpszTemp1)
1681     {
1682       LPSHELLFOLDER lpsfChild;
1683       WCHAR lpwstrTemp[MAX_PATH];
1684       DWORD dwEaten, dwAttributes;
1685       LPWSTR p;
1686
1687       strcpyW(lpwstrTemp, lpszTemp);
1688       p = PathFindNextComponentW(lpwstrTemp);
1689
1690       if (!p) break; /* end of path */
1691
1692       *p = 0;
1693       lpszTemp = lpszTemp + strlenW(lpwstrTemp);
1694
1695       if(*lpszTemp==0)
1696       {
1697         WCHAR wszWild[] = { '*', '?', 0 };
1698         /* if the last element is a wildcard do a search */
1699         if(strpbrkW(lpszTemp1, wszWild) != NULL)
1700         {
1701           nOpenAction = ONOPEN_SEARCH;
1702           break;
1703         }
1704       }
1705       lpszTemp1 = lpszTemp;
1706
1707       TRACE("parse now=%s next=%s sf=%p\n",debugstr_w(lpwstrTemp), debugstr_w(lpszTemp), lpsf);
1708
1709       if(lstrlenW(lpwstrTemp)==2) PathAddBackslashW(lpwstrTemp);
1710
1711       dwAttributes = SFGAO_FOLDER;
1712       if(SUCCEEDED(IShellFolder_ParseDisplayName(lpsf, hwnd, NULL, lpwstrTemp, &dwEaten, &pidl, &dwAttributes)))
1713       {
1714         /* the path component is valid, we have a pidl of the next path component */
1715         TRACE("parse OK attr=0x%08lx pidl=%p\n", dwAttributes, pidl);
1716         if(dwAttributes & SFGAO_FOLDER)
1717         {
1718           if(FAILED(IShellFolder_BindToObject(lpsf, pidl, 0, &IID_IShellFolder, (LPVOID*)&lpsfChild)))
1719           {
1720             ERR("bind to failed\n"); /* should not fail */
1721             break;
1722           }
1723           IShellFolder_Release(lpsf);
1724           lpsf = lpsfChild;
1725           lpsfChild = NULL;
1726         }
1727         else
1728         {
1729           TRACE("value\n");
1730
1731           /* end dialog, return value */
1732           nOpenAction = ONOPEN_OPEN;
1733           break;
1734         }
1735         COMDLG32_SHFree(pidl);
1736         pidl = NULL;
1737       }
1738       else if (!(fodInfos->ofnInfos->Flags & OFN_NOVALIDATE))
1739       {
1740         if(*lpszTemp)   /* points to trailing null for last path element */
1741         {
1742           if(fodInfos->ofnInfos->Flags & OFN_PATHMUSTEXIST)
1743           {
1744             FILEDLG95_OnOpenMessage(hwnd, 0, IDS_PATHNOTEXISTING);
1745             break;
1746           }
1747         }
1748         else
1749         {
1750           if( (fodInfos->ofnInfos->Flags & OFN_FILEMUSTEXIST) &&
1751              !( fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG ) )
1752           {
1753             FILEDLG95_OnOpenMessage(hwnd, 0, IDS_FILENOTEXISTING);
1754             break;
1755           }
1756         }
1757         /* change to the current folder */
1758         nOpenAction = ONOPEN_OPEN;
1759         break;
1760       }
1761       else
1762       {
1763         nOpenAction = ONOPEN_OPEN;
1764         break;
1765       }
1766     }
1767     if(pidl) COMDLG32_SHFree(pidl);
1768   }
1769
1770 /*
1771   Step 3: here we have a cleaned up and validated path
1772
1773   valid variables:
1774    lpsf:             ShellFolder bound to the rightmost valid path component
1775    lpstrPathAndFile: cleaned up path
1776    nOpenAction:      action to do
1777 */
1778   TRACE("end validate sf=%p\n", lpsf);
1779
1780   switch(nOpenAction)
1781   {
1782     case ONOPEN_SEARCH:   /* set the current filter to the file mask and refresh */
1783       TRACE("ONOPEN_SEARCH %s\n", debugstr_w(lpstrPathAndFile));
1784       {
1785         int iPos;
1786         LPWSTR lpszTemp = PathFindFileNameW(lpstrPathAndFile);
1787         DWORD len;
1788
1789         /* replace the current filter */
1790         if(fodInfos->ShellInfos.lpstrCurrentFilter)
1791           MemFree((LPVOID)fodInfos->ShellInfos.lpstrCurrentFilter);
1792         len = strlenW(lpszTemp)+1;
1793         fodInfos->ShellInfos.lpstrCurrentFilter = MemAlloc(len * sizeof(WCHAR));
1794         strcpyW( fodInfos->ShellInfos.lpstrCurrentFilter, lpszTemp);
1795
1796         /* set the filter cb to the extension when possible */
1797         if(-1 < (iPos = FILEDLG95_FILETYPE_SearchExt(fodInfos->DlgInfos.hwndFileTypeCB, lpszTemp)))
1798         CBSetCurSel(fodInfos->DlgInfos.hwndFileTypeCB, iPos);
1799       }
1800       /* fall through */
1801     case ONOPEN_BROWSE:   /* browse to the highest folder we could bind to */
1802       TRACE("ONOPEN_BROWSE\n");
1803       {
1804         IPersistFolder2 * ppf2;
1805         if(SUCCEEDED(IShellFolder_QueryInterface( lpsf, &IID_IPersistFolder2, (LPVOID*)&ppf2)))
1806         {
1807           LPITEMIDLIST pidlCurrent;
1808           IPersistFolder2_GetCurFolder(ppf2, &pidlCurrent);
1809           IPersistFolder2_Release(ppf2);
1810           if( ! COMDLG32_PIDL_ILIsEqual(pidlCurrent, fodInfos->ShellInfos.pidlAbsCurrent))
1811           {
1812             IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser, pidlCurrent, SBSP_ABSOLUTE);
1813           }
1814           else if( nOpenAction == ONOPEN_SEARCH )
1815           {
1816             IShellView_Refresh(fodInfos->Shell.FOIShellView);
1817           }
1818           COMDLG32_SHFree(pidlCurrent);
1819         }
1820       }
1821       ret = FALSE;
1822       break;
1823     case ONOPEN_OPEN:   /* fill in the return struct and close the dialog */
1824       TRACE("ONOPEN_OPEN %s\n", debugstr_w(lpstrPathAndFile));
1825       {
1826         /* add default extension */
1827         if (fodInfos->defext)
1828         {
1829           if (! *PathFindExtensionW(lpstrPathAndFile))
1830           {
1831             /* only add "." in case a default extension does exist */
1832             if (*fodInfos->defext != '\0')
1833             {
1834                 const WCHAR szwDot[] = {'.',0};
1835                 int PathLength = strlenW(lpstrPathAndFile);
1836
1837                 strcatW(lpstrPathAndFile, szwDot);
1838                 strcatW(lpstrPathAndFile, fodInfos->defext);
1839
1840                 /* if file does not exist try without extension */
1841                 if (!PathFileExistsW(lpstrPathAndFile))
1842                   lpstrPathAndFile[PathLength] = '\0';
1843             }
1844           }
1845         }
1846
1847         /* Check that the size of the file does not exceed buffer size.
1848              (Allow for extra \0 if OFN_MULTISELECT is set.) */
1849         if(strlenW(lpstrPathAndFile) < fodInfos->ofnInfos->nMaxFile -
1850             ((fodInfos->ofnInfos->Flags & OFN_ALLOWMULTISELECT) ? 1 : 0))
1851         {
1852           LPWSTR lpszTemp;
1853
1854           /* fill destination buffer */
1855           if (fodInfos->ofnInfos->lpstrFile)
1856           {
1857              if(fodInfos->unicode)
1858              {
1859                LPOPENFILENAMEW ofn = (LPOPENFILENAMEW) fodInfos->ofnInfos;
1860
1861                strncpyW(ofn->lpstrFile, lpstrPathAndFile, ofn->nMaxFile);
1862                if (ofn->Flags & OFN_ALLOWMULTISELECT)
1863                  ofn->lpstrFile[lstrlenW(ofn->lpstrFile) + 1] = '\0';
1864              }
1865              else
1866              {
1867                LPOPENFILENAMEA ofn = fodInfos->ofnInfos;
1868
1869                WideCharToMultiByte(CP_ACP, 0, lpstrPathAndFile, -1,
1870                                    ofn->lpstrFile, ofn->nMaxFile, NULL, NULL);
1871                if (ofn->Flags & OFN_ALLOWMULTISELECT)
1872                  ofn->lpstrFile[lstrlenA(ofn->lpstrFile) + 1] = '\0';
1873              }
1874           }
1875
1876           /* set filename offset */
1877           lpszTemp = PathFindFileNameW(lpstrPathAndFile);
1878           fodInfos->ofnInfos->nFileOffset = (lpszTemp - lpstrPathAndFile);
1879
1880           /* set extension offset */
1881           lpszTemp = PathFindExtensionW(lpstrPathAndFile);
1882           fodInfos->ofnInfos->nFileExtension = (*lpszTemp) ? (lpszTemp - lpstrPathAndFile) + 1 : 0;
1883
1884           /* set the lpstrFileTitle */
1885           if(fodInfos->ofnInfos->lpstrFileTitle)
1886           {
1887             LPWSTR lpstrFileTitle = PathFindFileNameW(lpstrPathAndFile);
1888             if(fodInfos->unicode)
1889             {
1890               LPOPENFILENAMEW ofn = (LPOPENFILENAMEW) fodInfos->ofnInfos;
1891               strncpyW(ofn->lpstrFileTitle, lpstrFileTitle, ofn->nMaxFileTitle);
1892             }
1893             else
1894             {
1895               LPOPENFILENAMEA ofn = fodInfos->ofnInfos;
1896               WideCharToMultiByte(CP_ACP, 0, lpstrFileTitle, -1,
1897                     ofn->lpstrFileTitle, ofn->nMaxFileTitle, NULL, NULL);
1898             }
1899           }
1900
1901           if ( !FILEDLG95_SendFileOK(hwnd, fodInfos) )
1902               goto ret;
1903
1904           TRACE("close\n");
1905           FILEDLG95_Clean(hwnd);
1906           ret = EndDialog(hwnd, TRUE);
1907         }
1908         else
1909         {
1910           /* FIXME set error FNERR_BUFFERTOSMALL */
1911           FILEDLG95_Clean(hwnd);
1912           ret = EndDialog(hwnd, FALSE);
1913         }
1914         goto ret;
1915       }
1916       break;
1917   }
1918
1919 ret:
1920   if(lpsf) IShellFolder_Release(lpsf);
1921   return ret;
1922 }
1923
1924 /***********************************************************************
1925  *      FILEDLG95_SHELL_Init
1926  *
1927  * Initialisation of the shell objects
1928  */
1929 static HRESULT FILEDLG95_SHELL_Init(HWND hwnd)
1930 {
1931   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
1932
1933   TRACE("\n");
1934
1935   /*
1936    * Initialisation of the FileOpenDialogInfos structure
1937    */
1938
1939   /* Shell */
1940
1941   /*ShellInfos */
1942   fodInfos->ShellInfos.hwndOwner = hwnd;
1943
1944   /* Disable multi-select if flag not set */
1945   if (!(fodInfos->ofnInfos->Flags & OFN_ALLOWMULTISELECT))
1946   {
1947      fodInfos->ShellInfos.folderSettings.fFlags |= FWF_SINGLESEL;
1948   }
1949   fodInfos->ShellInfos.folderSettings.fFlags |= FWF_AUTOARRANGE | FWF_ALIGNLEFT;
1950   fodInfos->ShellInfos.folderSettings.ViewMode = FVM_LIST;
1951
1952   GetWindowRect(GetDlgItem(hwnd,IDC_SHELLSTATIC),&fodInfos->ShellInfos.rectView);
1953   ScreenToClient(hwnd,(LPPOINT)&fodInfos->ShellInfos.rectView.left);
1954   ScreenToClient(hwnd,(LPPOINT)&fodInfos->ShellInfos.rectView.right);
1955
1956   /* Construct the IShellBrowser interface */
1957   fodInfos->Shell.FOIShellBrowser = IShellBrowserImpl_Construct(hwnd);
1958
1959   return NOERROR;
1960 }
1961
1962 /***********************************************************************
1963  *      FILEDLG95_SHELL_ExecuteCommand
1964  *
1965  * Change the folder option and refresh the view
1966  * If the function succeeds, the return value is nonzero.
1967  */
1968 static BOOL FILEDLG95_SHELL_ExecuteCommand(HWND hwnd, LPCSTR lpVerb)
1969 {
1970   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
1971
1972   IContextMenu * pcm;
1973   TRACE("(%p,%p)\n", hwnd, lpVerb);
1974
1975   if(SUCCEEDED(IShellView_GetItemObject(fodInfos->Shell.FOIShellView,
1976                                         SVGIO_BACKGROUND,
1977                                         &IID_IContextMenu,
1978                                         (LPVOID*)&pcm)))
1979   {
1980     CMINVOKECOMMANDINFO ci;
1981     ZeroMemory(&ci, sizeof(CMINVOKECOMMANDINFO));
1982     ci.cbSize = sizeof(CMINVOKECOMMANDINFO);
1983     ci.lpVerb = lpVerb;
1984     ci.hwnd = hwnd;
1985
1986     IContextMenu_InvokeCommand(pcm, &ci);
1987     IContextMenu_Release(pcm);
1988   }
1989
1990   return FALSE;
1991 }
1992
1993 /***********************************************************************
1994  *      FILEDLG95_SHELL_UpFolder
1995  *
1996  * Browse to the specified object
1997  * If the function succeeds, the return value is nonzero.
1998  */
1999 static BOOL FILEDLG95_SHELL_UpFolder(HWND hwnd)
2000 {
2001   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2002
2003   TRACE("\n");
2004
2005   if(SUCCEEDED(IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser,
2006                                           NULL,
2007                                           SBSP_PARENT)))
2008   {
2009     return TRUE;
2010   }
2011   return FALSE;
2012 }
2013
2014 /***********************************************************************
2015  *      FILEDLG95_SHELL_BrowseToDesktop
2016  *
2017  * Browse to the Desktop
2018  * If the function succeeds, the return value is nonzero.
2019  */
2020 static BOOL FILEDLG95_SHELL_BrowseToDesktop(HWND hwnd)
2021 {
2022   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2023   LPITEMIDLIST pidl;
2024   HRESULT hres;
2025
2026   TRACE("\n");
2027
2028   SHGetSpecialFolderLocation(0,CSIDL_DESKTOP,&pidl);
2029   hres = IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser, pidl, SBSP_ABSOLUTE);
2030   COMDLG32_SHFree(pidl);
2031   return SUCCEEDED(hres);
2032 }
2033 /***********************************************************************
2034  *      FILEDLG95_SHELL_Clean
2035  *
2036  * Cleans the memory used by shell objects
2037  */
2038 static void FILEDLG95_SHELL_Clean(HWND hwnd)
2039 {
2040     FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2041
2042     TRACE("\n");
2043
2044     COMDLG32_SHFree(fodInfos->ShellInfos.pidlAbsCurrent);
2045
2046     /* clean Shell interfaces */
2047     IShellView_DestroyViewWindow(fodInfos->Shell.FOIShellView);
2048     IShellView_Release(fodInfos->Shell.FOIShellView);
2049     IShellFolder_Release(fodInfos->Shell.FOIShellFolder);
2050     IShellBrowser_Release(fodInfos->Shell.FOIShellBrowser);
2051     if (fodInfos->Shell.FOIDataObject)
2052       IDataObject_Release(fodInfos->Shell.FOIDataObject);
2053 }
2054
2055 /***********************************************************************
2056  *      FILEDLG95_FILETYPE_Init
2057  *
2058  * Initialisation of the file type combo box
2059  */
2060 static HRESULT FILEDLG95_FILETYPE_Init(HWND hwnd)
2061 {
2062   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2063
2064   TRACE("\n");
2065
2066   if(fodInfos->filter)
2067   {
2068     int nFilters = 0;   /* number of filters */
2069     LPWSTR lpstrFilter;
2070     LPCWSTR lpstrPos = fodInfos->filter;
2071
2072     for(;;)
2073     {
2074       /* filter is a list...  title\0ext\0......\0\0
2075        * Set the combo item text to the title and the item data
2076        *  to the ext
2077        */
2078       LPCWSTR lpstrDisplay;
2079       LPWSTR lpstrExt;
2080
2081       /* Get the title */
2082       if(! *lpstrPos) break;    /* end */
2083       lpstrDisplay = lpstrPos;
2084       lpstrPos += strlenW(lpstrPos) + 1;
2085
2086       /* Copy the extensions */
2087       if (! *lpstrPos) return E_FAIL;   /* malformed filter */
2088       if (!(lpstrExt = MemAlloc((strlenW(lpstrPos)+1)*sizeof(WCHAR)))) return E_FAIL;
2089       strcpyW(lpstrExt,lpstrPos);
2090       lpstrPos += strlenW(lpstrPos) + 1;
2091
2092       /* Add the item at the end of the combo */
2093       CBAddStringW(fodInfos->DlgInfos.hwndFileTypeCB, lpstrDisplay);
2094       CBSetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB, nFilters, lpstrExt);
2095       nFilters++;
2096     }
2097     /*
2098      * Set the current filter to the one specified
2099      * in the initialisation structure
2100      * FIXME: lpstrCustomFilter not handled at all
2101      */
2102
2103     /* set default filter index */
2104     if(fodInfos->ofnInfos->nFilterIndex == 0 && fodInfos->customfilter == NULL)
2105       fodInfos->ofnInfos->nFilterIndex = 1;
2106
2107     /* First, check to make sure our index isn't out of bounds. */
2108     if ( fodInfos->ofnInfos->nFilterIndex > nFilters )
2109       fodInfos->ofnInfos->nFilterIndex = nFilters;
2110
2111     /* Set the current index selection. */
2112     CBSetCurSel(fodInfos->DlgInfos.hwndFileTypeCB, fodInfos->ofnInfos->nFilterIndex-1);
2113
2114     /* Get the corresponding text string from the combo box. */
2115     lpstrFilter = (LPWSTR) CBGetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB,
2116                                              fodInfos->ofnInfos->nFilterIndex-1);
2117
2118     if ((INT)lpstrFilter == CB_ERR)  /* control is empty */
2119       lpstrFilter = NULL;
2120
2121     if(lpstrFilter)
2122     {
2123       DWORD len;
2124       CharLowerW(lpstrFilter); /* lowercase */
2125       len = strlenW(lpstrFilter)+1;
2126       fodInfos->ShellInfos.lpstrCurrentFilter = MemAlloc( len * sizeof(WCHAR) );
2127       strcpyW(fodInfos->ShellInfos.lpstrCurrentFilter,lpstrFilter);
2128     }
2129   }
2130   return NOERROR;
2131 }
2132
2133 /***********************************************************************
2134  *      FILEDLG95_FILETYPE_OnCommand
2135  *
2136  * WM_COMMAND of the file type combo box
2137  * If the function succeeds, the return value is nonzero.
2138  */
2139 static BOOL FILEDLG95_FILETYPE_OnCommand(HWND hwnd, WORD wNotifyCode)
2140 {
2141   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2142
2143   switch(wNotifyCode)
2144   {
2145     case CBN_SELENDOK:
2146     {
2147       LPWSTR lpstrFilter;
2148
2149       /* Get the current item of the filetype combo box */
2150       int iItem = CBGetCurSel(fodInfos->DlgInfos.hwndFileTypeCB);
2151
2152       /* set the current filter index - indexed from 1 */
2153       fodInfos->ofnInfos->nFilterIndex = iItem + 1;
2154
2155       /* Set the current filter with the current selection */
2156       if(fodInfos->ShellInfos.lpstrCurrentFilter)
2157          MemFree((LPVOID)fodInfos->ShellInfos.lpstrCurrentFilter);
2158
2159       lpstrFilter = (LPWSTR) CBGetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB,
2160                                              iItem);
2161       if((int)lpstrFilter != CB_ERR)
2162       {
2163           DWORD len;
2164           CharLowerW(lpstrFilter); /* lowercase */
2165           len = strlenW(lpstrFilter)+1;
2166           fodInfos->ShellInfos.lpstrCurrentFilter = MemAlloc( len * sizeof(WCHAR) );
2167           strcpyW(fodInfos->ShellInfos.lpstrCurrentFilter,lpstrFilter);
2168           SendCustomDlgNotificationMessage(hwnd,CDN_TYPECHANGE);
2169       }
2170
2171       /* Refresh the actual view to display the included items*/
2172       IShellView_Refresh(fodInfos->Shell.FOIShellView);
2173     }
2174   }
2175   return FALSE;
2176 }
2177 /***********************************************************************
2178  *      FILEDLG95_FILETYPE_SearchExt
2179  *
2180  * searches for a extension in the filetype box
2181  */
2182 static int FILEDLG95_FILETYPE_SearchExt(HWND hwnd,LPCWSTR lpstrExt)
2183 {
2184   int i, iCount = CBGetCount(hwnd);
2185
2186   TRACE("%s\n", debugstr_w(lpstrExt));
2187
2188   if(iCount != CB_ERR)
2189   {
2190     for(i=0;i<iCount;i++)
2191     {
2192       if(!lstrcmpiW(lpstrExt,(LPWSTR)CBGetItemDataPtr(hwnd,i)))
2193           return i;
2194     }
2195   }
2196   return -1;
2197 }
2198
2199 /***********************************************************************
2200  *      FILEDLG95_FILETYPE_Clean
2201  *
2202  * Clean the memory used by the filetype combo box
2203  */
2204 static void FILEDLG95_FILETYPE_Clean(HWND hwnd)
2205 {
2206   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2207   int iPos;
2208   int iCount = CBGetCount(fodInfos->DlgInfos.hwndFileTypeCB);
2209
2210   TRACE("\n");
2211
2212   /* Delete each string of the combo and their associated data */
2213   if(iCount != CB_ERR)
2214   {
2215     for(iPos = iCount-1;iPos>=0;iPos--)
2216     {
2217       MemFree((LPSTR) CBGetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB,iPos));
2218       CBDeleteString(fodInfos->DlgInfos.hwndFileTypeCB,iPos);
2219     }
2220   }
2221   /* Current filter */
2222   if(fodInfos->ShellInfos.lpstrCurrentFilter)
2223      MemFree(fodInfos->ShellInfos.lpstrCurrentFilter);
2224
2225 }
2226
2227 /***********************************************************************
2228  *      FILEDLG95_LOOKIN_Init
2229  *
2230  * Initialisation of the look in combo box
2231  */
2232 static HRESULT FILEDLG95_LOOKIN_Init(HWND hwndCombo)
2233 {
2234   IShellFolder  *psfRoot, *psfDrives;
2235   IEnumIDList   *lpeRoot, *lpeDrives;
2236   LPITEMIDLIST  pidlDrives, pidlTmp, pidlTmp1, pidlAbsTmp;
2237
2238   LookInInfos *liInfos = MemAlloc(sizeof(LookInInfos));
2239
2240   TRACE("\n");
2241
2242   liInfos->iMaxIndentation = 0;
2243
2244   SetPropA(hwndCombo, LookInInfosStr, (HANDLE) liInfos);
2245
2246   /* set item height for both text field and listbox */
2247   CBSetItemHeight(hwndCombo,-1,GetSystemMetrics(SM_CYSMICON));
2248   CBSetItemHeight(hwndCombo,0,GetSystemMetrics(SM_CYSMICON));
2249
2250   /* Initialise data of Desktop folder */
2251   SHGetSpecialFolderLocation(0,CSIDL_DESKTOP,&pidlTmp);
2252   FILEDLG95_LOOKIN_AddItem(hwndCombo, pidlTmp,LISTEND);
2253   COMDLG32_SHFree(pidlTmp);
2254
2255   SHGetSpecialFolderLocation(0,CSIDL_DRIVES,&pidlDrives);
2256
2257   SHGetDesktopFolder(&psfRoot);
2258
2259   if (psfRoot)
2260   {
2261     /* enumerate the contents of the desktop */
2262     if(SUCCEEDED(IShellFolder_EnumObjects(psfRoot, hwndCombo, SHCONTF_FOLDERS, &lpeRoot)))
2263     {
2264       while (S_OK == IEnumIDList_Next(lpeRoot, 1, &pidlTmp, NULL))
2265       {
2266         FILEDLG95_LOOKIN_AddItem(hwndCombo, pidlTmp,LISTEND);
2267
2268         /* special handling for CSIDL_DRIVES */
2269         if (COMDLG32_PIDL_ILIsEqual(pidlTmp, pidlDrives))
2270         {
2271           if(SUCCEEDED(IShellFolder_BindToObject(psfRoot, pidlTmp, NULL, &IID_IShellFolder, (LPVOID*)&psfDrives)))
2272           {
2273             /* enumerate the drives */
2274             if(SUCCEEDED(IShellFolder_EnumObjects(psfDrives, hwndCombo,SHCONTF_FOLDERS, &lpeDrives)))
2275             {
2276               while (S_OK == IEnumIDList_Next(lpeDrives, 1, &pidlTmp1, NULL))
2277               {
2278                 pidlAbsTmp = COMDLG32_PIDL_ILCombine(pidlTmp, pidlTmp1);
2279                 FILEDLG95_LOOKIN_AddItem(hwndCombo, pidlAbsTmp,LISTEND);
2280                 COMDLG32_SHFree(pidlAbsTmp);
2281                 COMDLG32_SHFree(pidlTmp1);
2282               }
2283               IEnumIDList_Release(lpeDrives);
2284             }
2285             IShellFolder_Release(psfDrives);
2286           }
2287         }
2288         COMDLG32_SHFree(pidlTmp);
2289       }
2290       IEnumIDList_Release(lpeRoot);
2291     }
2292   }
2293
2294   IShellFolder_Release(psfRoot);
2295   COMDLG32_SHFree(pidlDrives);
2296   return NOERROR;
2297 }
2298
2299 /***********************************************************************
2300  *      FILEDLG95_LOOKIN_DrawItem
2301  *
2302  * WM_DRAWITEM message handler
2303  */
2304 static LRESULT FILEDLG95_LOOKIN_DrawItem(LPDRAWITEMSTRUCT pDIStruct)
2305 {
2306   COLORREF crWin = GetSysColor(COLOR_WINDOW);
2307   COLORREF crHighLight = GetSysColor(COLOR_HIGHLIGHT);
2308   COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
2309   RECT rectText;
2310   RECT rectIcon;
2311   SHFILEINFOA sfi;
2312   HIMAGELIST ilItemImage;
2313   int iIndentation;
2314   TEXTMETRICA tm;
2315   LPSFOLDER tmpFolder;
2316
2317
2318   LookInInfos *liInfos = (LookInInfos *)GetPropA(pDIStruct->hwndItem,LookInInfosStr);
2319
2320   TRACE("\n");
2321
2322   if(pDIStruct->itemID == -1)
2323     return 0;
2324
2325   if(!(tmpFolder = (LPSFOLDER) CBGetItemDataPtr(pDIStruct->hwndItem,
2326                             pDIStruct->itemID)))
2327     return 0;
2328
2329
2330   if(pDIStruct->itemID == liInfos->uSelectedItem)
2331   {
2332     ilItemImage = (HIMAGELIST) SHGetFileInfoA ((LPCSTR) tmpFolder->pidlItem,
2333                                                0,
2334                                                &sfi,
2335                                                sizeof (SHFILEINFOA),
2336                                                SHGFI_PIDL | SHGFI_SMALLICON |
2337                                                SHGFI_OPENICON | SHGFI_SYSICONINDEX    |
2338                                                SHGFI_DISPLAYNAME );
2339   }
2340   else
2341   {
2342     ilItemImage = (HIMAGELIST) SHGetFileInfoA ((LPCSTR) tmpFolder->pidlItem,
2343                                                   0,
2344                                                   &sfi,
2345                                                   sizeof (SHFILEINFOA),
2346                                                   SHGFI_PIDL | SHGFI_SMALLICON |
2347                                                   SHGFI_SYSICONINDEX |
2348                                                   SHGFI_DISPLAYNAME);
2349   }
2350
2351   /* Is this item selected ? */
2352   if(pDIStruct->itemState & ODS_SELECTED)
2353   {
2354     SetTextColor(pDIStruct->hDC,(0x00FFFFFF & ~(crText)));
2355     SetBkColor(pDIStruct->hDC,crHighLight);
2356     FillRect(pDIStruct->hDC,&pDIStruct->rcItem,GetSysColorBrush(COLOR_HIGHLIGHT));
2357   }
2358   else
2359   {
2360     SetTextColor(pDIStruct->hDC,crText);
2361     SetBkColor(pDIStruct->hDC,crWin);
2362     FillRect(pDIStruct->hDC,&pDIStruct->rcItem,GetSysColorBrush(COLOR_WINDOW));
2363   }
2364
2365   /* Do not indent item if drawing in the edit of the combo */
2366   if(pDIStruct->itemState & ODS_COMBOBOXEDIT)
2367   {
2368     iIndentation = 0;
2369     ilItemImage = (HIMAGELIST) SHGetFileInfoA ((LPCSTR) tmpFolder->pidlItem,
2370                                                 0,
2371                                                 &sfi,
2372                                                 sizeof (SHFILEINFOA),
2373                                                 SHGFI_PIDL | SHGFI_SMALLICON | SHGFI_OPENICON
2374                                                 | SHGFI_SYSICONINDEX | SHGFI_DISPLAYNAME  );
2375
2376   }
2377   else
2378   {
2379     iIndentation = tmpFolder->m_iIndent;
2380   }
2381   /* Draw text and icon */
2382
2383   /* Initialise the icon display area */
2384   rectIcon.left = pDIStruct->rcItem.left + ICONWIDTH/2 * iIndentation;
2385   rectIcon.top = pDIStruct->rcItem.top;
2386   rectIcon.right = rectIcon.left + ICONWIDTH;
2387   rectIcon.bottom = pDIStruct->rcItem.bottom;
2388
2389   /* Initialise the text display area */
2390   GetTextMetricsA(pDIStruct->hDC, &tm);
2391   rectText.left = rectIcon.right;
2392   rectText.top =
2393           (pDIStruct->rcItem.top + pDIStruct->rcItem.bottom - tm.tmHeight) / 2;
2394   rectText.right = pDIStruct->rcItem.right + XTEXTOFFSET;
2395   rectText.bottom =
2396           (pDIStruct->rcItem.top + pDIStruct->rcItem.bottom + tm.tmHeight) / 2;
2397
2398   /* Draw the icon from the image list */
2399   ImageList_Draw(ilItemImage,
2400                  sfi.iIcon,
2401                  pDIStruct->hDC,
2402                  rectIcon.left,
2403                  rectIcon.top,
2404                  ILD_TRANSPARENT );
2405
2406   /* Draw the associated text */
2407   if(sfi.szDisplayName)
2408     TextOutA(pDIStruct->hDC,rectText.left,rectText.top,sfi.szDisplayName,strlen(sfi.szDisplayName));
2409
2410
2411   return NOERROR;
2412 }
2413
2414 /***********************************************************************
2415  *      FILEDLG95_LOOKIN_OnCommand
2416  *
2417  * LookIn combo box WM_COMMAND message handler
2418  * If the function succeeds, the return value is nonzero.
2419  */
2420 static BOOL FILEDLG95_LOOKIN_OnCommand(HWND hwnd, WORD wNotifyCode)
2421 {
2422   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2423
2424   TRACE("%p\n", fodInfos);
2425
2426   switch(wNotifyCode)
2427   {
2428     case CBN_SELENDOK:
2429     {
2430       LPSFOLDER tmpFolder;
2431       int iItem;
2432
2433       iItem = CBGetCurSel(fodInfos->DlgInfos.hwndLookInCB);
2434
2435       if(!(tmpFolder = (LPSFOLDER) CBGetItemDataPtr(fodInfos->DlgInfos.hwndLookInCB,
2436                                                iItem)))
2437         return FALSE;
2438
2439
2440       if(SUCCEEDED(IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser,
2441                                               tmpFolder->pidlItem,
2442                                               SBSP_ABSOLUTE)))
2443       {
2444         return TRUE;
2445       }
2446       break;
2447     }
2448
2449   }
2450   return FALSE;
2451 }
2452
2453 /***********************************************************************
2454  *      FILEDLG95_LOOKIN_AddItem
2455  *
2456  * Adds an absolute pidl item to the lookin combo box
2457  * returns the index of the inserted item
2458  */
2459 static int FILEDLG95_LOOKIN_AddItem(HWND hwnd,LPITEMIDLIST pidl, int iInsertId)
2460 {
2461   LPITEMIDLIST pidlNext;
2462   SHFILEINFOA sfi;
2463   SFOLDER *tmpFolder;
2464   LookInInfos *liInfos;
2465
2466   TRACE("%08x\n", iInsertId);
2467
2468   if(!pidl)
2469     return -1;
2470
2471   if(!(liInfos = (LookInInfos *)GetPropA(hwnd,LookInInfosStr)))
2472     return -1;
2473
2474   tmpFolder = MemAlloc(sizeof(SFOLDER));
2475   tmpFolder->m_iIndent = 0;
2476
2477   /* Calculate the indentation of the item in the lookin*/
2478   pidlNext = pidl;
2479   while( (pidlNext=COMDLG32_PIDL_ILGetNext(pidlNext)) )
2480   {
2481     tmpFolder->m_iIndent++;
2482   }
2483
2484   tmpFolder->pidlItem = COMDLG32_PIDL_ILClone(pidl);
2485
2486   if(tmpFolder->m_iIndent > liInfos->iMaxIndentation)
2487     liInfos->iMaxIndentation = tmpFolder->m_iIndent;
2488
2489   sfi.dwAttributes = SFGAO_FILESYSANCESTOR | SFGAO_FILESYSTEM;
2490   SHGetFileInfoA((LPSTR)pidl,
2491                   0,
2492                   &sfi,
2493                   sizeof(sfi),
2494                   SHGFI_DISPLAYNAME | SHGFI_SYSICONINDEX
2495                   | SHGFI_PIDL | SHGFI_SMALLICON | SHGFI_ATTRIBUTES | SHGFI_ATTR_SPECIFIED);
2496
2497   TRACE("-- Add %s attr=%08lx\n", sfi.szDisplayName, sfi.dwAttributes);
2498
2499   if((sfi.dwAttributes & SFGAO_FILESYSANCESTOR) || (sfi.dwAttributes & SFGAO_FILESYSTEM))
2500   {
2501     int iItemID;
2502
2503     TRACE("-- Add %s at %u\n", sfi.szDisplayName, tmpFolder->m_iIndent);
2504
2505     /* Add the item at the end of the list */
2506     if(iInsertId < 0)
2507     {
2508       iItemID = CBAddString(hwnd,sfi.szDisplayName);
2509     }
2510     /* Insert the item at the iInsertId position*/
2511     else
2512     {
2513       iItemID = CBInsertString(hwnd,sfi.szDisplayName,iInsertId);
2514     }
2515
2516     CBSetItemDataPtr(hwnd,iItemID,tmpFolder);
2517     return iItemID;
2518   }
2519
2520   COMDLG32_SHFree( tmpFolder->pidlItem );
2521   MemFree( tmpFolder );
2522   return -1;
2523
2524 }
2525
2526 /***********************************************************************
2527  *      FILEDLG95_LOOKIN_InsertItemAfterParent
2528  *
2529  * Insert an item below its parent
2530  */
2531 static int FILEDLG95_LOOKIN_InsertItemAfterParent(HWND hwnd,LPITEMIDLIST pidl)
2532 {
2533
2534   LPITEMIDLIST pidlParent = GetParentPidl(pidl);
2535   int iParentPos;
2536
2537   TRACE("\n");
2538
2539   iParentPos = FILEDLG95_LOOKIN_SearchItem(hwnd,(WPARAM)pidlParent,SEARCH_PIDL);
2540
2541   if(iParentPos < 0)
2542   {
2543     iParentPos = FILEDLG95_LOOKIN_InsertItemAfterParent(hwnd,pidlParent);
2544   }
2545
2546   /* Free pidlParent memory */
2547   COMDLG32_SHFree((LPVOID)pidlParent);
2548
2549   return FILEDLG95_LOOKIN_AddItem(hwnd,pidl,iParentPos + 1);
2550 }
2551
2552 /***********************************************************************
2553  *      FILEDLG95_LOOKIN_SelectItem
2554  *
2555  * Adds an absolute pidl item to the lookin combo box
2556  * returns the index of the inserted item
2557  */
2558 int FILEDLG95_LOOKIN_SelectItem(HWND hwnd,LPITEMIDLIST pidl)
2559 {
2560   int iItemPos;
2561   LookInInfos *liInfos;
2562
2563   TRACE("\n");
2564
2565   iItemPos = FILEDLG95_LOOKIN_SearchItem(hwnd,(WPARAM)pidl,SEARCH_PIDL);
2566
2567   liInfos = (LookInInfos *)GetPropA(hwnd,LookInInfosStr);
2568
2569   if(iItemPos < 0)
2570   {
2571     while(FILEDLG95_LOOKIN_RemoveMostExpandedItem(hwnd) > -1);
2572     iItemPos = FILEDLG95_LOOKIN_InsertItemAfterParent(hwnd,pidl);
2573   }
2574
2575   else
2576   {
2577     SFOLDER *tmpFolder = (LPSFOLDER) CBGetItemDataPtr(hwnd,iItemPos);
2578     while(liInfos->iMaxIndentation > tmpFolder->m_iIndent)
2579     {
2580       int iRemovedItem;
2581
2582       if(-1 == (iRemovedItem = FILEDLG95_LOOKIN_RemoveMostExpandedItem(hwnd)))
2583         break;
2584       if(iRemovedItem < iItemPos)
2585         iItemPos--;
2586     }
2587   }
2588
2589   CBSetCurSel(hwnd,iItemPos);
2590   liInfos->uSelectedItem = iItemPos;
2591
2592   return 0;
2593
2594 }
2595
2596 /***********************************************************************
2597  *      FILEDLG95_LOOKIN_RemoveMostExpandedItem
2598  *
2599  * Remove the item with an expansion level over iExpansionLevel
2600  */
2601 static int FILEDLG95_LOOKIN_RemoveMostExpandedItem(HWND hwnd)
2602 {
2603   int iItemPos;
2604
2605   LookInInfos *liInfos = (LookInInfos *)GetPropA(hwnd,LookInInfosStr);
2606
2607   TRACE("\n");
2608
2609   if(liInfos->iMaxIndentation <= 2)
2610     return -1;
2611
2612   if((iItemPos = FILEDLG95_LOOKIN_SearchItem(hwnd,(WPARAM)liInfos->iMaxIndentation,SEARCH_EXP)) >=0)
2613   {
2614     SFOLDER *tmpFolder = (LPSFOLDER) CBGetItemDataPtr(hwnd,iItemPos);
2615     COMDLG32_SHFree(tmpFolder->pidlItem);
2616     MemFree(tmpFolder);
2617     CBDeleteString(hwnd,iItemPos);
2618     liInfos->iMaxIndentation--;
2619
2620     return iItemPos;
2621   }
2622
2623   return -1;
2624 }
2625
2626 /***********************************************************************
2627  *      FILEDLG95_LOOKIN_SearchItem
2628  *
2629  * Search for pidl in the lookin combo box
2630  * returns the index of the found item
2631  */
2632 static int FILEDLG95_LOOKIN_SearchItem(HWND hwnd,WPARAM searchArg,int iSearchMethod)
2633 {
2634   int i = 0;
2635   int iCount = CBGetCount(hwnd);
2636
2637   TRACE("0x%08x 0x%x\n",searchArg, iSearchMethod);
2638
2639   if (iCount != CB_ERR)
2640   {
2641     for(;i<iCount;i++)
2642     {
2643       LPSFOLDER tmpFolder = (LPSFOLDER) CBGetItemDataPtr(hwnd,i);
2644
2645       if(iSearchMethod == SEARCH_PIDL && COMDLG32_PIDL_ILIsEqual((LPITEMIDLIST)searchArg,tmpFolder->pidlItem))
2646         return i;
2647       if(iSearchMethod == SEARCH_EXP && tmpFolder->m_iIndent == (int)searchArg)
2648         return i;
2649     }
2650   }
2651
2652   return -1;
2653 }
2654
2655 /***********************************************************************
2656  *      FILEDLG95_LOOKIN_Clean
2657  *
2658  * Clean the memory used by the lookin combo box
2659  */
2660 static void FILEDLG95_LOOKIN_Clean(HWND hwnd)
2661 {
2662     FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2663     int iPos;
2664     int iCount = CBGetCount(fodInfos->DlgInfos.hwndLookInCB);
2665
2666     TRACE("\n");
2667
2668     /* Delete each string of the combo and their associated data */
2669     if (iCount != CB_ERR)
2670     {
2671       for(iPos = iCount-1;iPos>=0;iPos--)
2672       {
2673         SFOLDER *tmpFolder = (LPSFOLDER) CBGetItemDataPtr(fodInfos->DlgInfos.hwndLookInCB,iPos);
2674         COMDLG32_SHFree(tmpFolder->pidlItem);
2675         MemFree(tmpFolder);
2676         CBDeleteString(fodInfos->DlgInfos.hwndLookInCB,iPos);
2677       }
2678     }
2679
2680     /* LookInInfos structure */
2681     RemovePropA(fodInfos->DlgInfos.hwndLookInCB,LookInInfosStr);
2682
2683 }
2684 /***********************************************************************
2685  * FILEDLG95_FILENAME_FillFromSelection
2686  *
2687  * fills the edit box from the cached DataObject
2688  */
2689 void FILEDLG95_FILENAME_FillFromSelection (HWND hwnd)
2690 {
2691     FileOpenDlgInfos *fodInfos;
2692     LPITEMIDLIST      pidl;
2693     UINT              nFiles = 0, nFileToOpen, nFileSelected, nLength = 0;
2694     char              lpstrTemp[MAX_PATH];
2695     LPSTR             lpstrAllFile = NULL, lpstrCurrFile = NULL;
2696
2697     TRACE("\n");
2698     fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2699
2700     /* Count how many files we have */
2701     nFileSelected = GetNumSelected( fodInfos->Shell.FOIDataObject );
2702
2703     /* calculate the string length, count files */
2704     if (nFileSelected >= 1)
2705     {
2706       nLength += 3;     /* first and last quotes, trailing \0 */
2707       for ( nFileToOpen = 0; nFileToOpen < nFileSelected; nFileToOpen++ )
2708       {
2709         pidl = GetPidlFromDataObject( fodInfos->Shell.FOIDataObject, nFileToOpen+1 );
2710
2711         if (pidl)
2712         {
2713           /* get the total length of the selected file names*/
2714           lpstrTemp[0] = '\0';
2715           GetName( fodInfos->Shell.FOIShellFolder, pidl, SHGDN_INFOLDER|SHGDN_FORPARSING, lpstrTemp );
2716
2717           if ( ! IsPidlFolder(fodInfos->Shell.FOIShellFolder, pidl) ) /* Ignore folders */
2718           {
2719             nLength += strlen( lpstrTemp ) + 3;
2720             nFiles++;
2721           }
2722           COMDLG32_SHFree( pidl );
2723         }
2724       }
2725     }
2726
2727     /* allocate the buffer */
2728     if (nFiles <= 1) nLength = MAX_PATH;
2729     lpstrAllFile = (LPSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nLength);
2730     lpstrAllFile[0] = '\0';
2731
2732     /* Generate the string for the edit control */
2733     if(nFiles >= 1)
2734     {
2735       lpstrCurrFile = lpstrAllFile;
2736       for ( nFileToOpen = 0; nFileToOpen < nFileSelected; nFileToOpen++ )
2737       {
2738         pidl = GetPidlFromDataObject( fodInfos->Shell.FOIDataObject, nFileToOpen+1 );
2739
2740         if (pidl)
2741         {
2742           /* get the file name */
2743           lpstrTemp[0] = '\0';
2744           GetName( fodInfos->Shell.FOIShellFolder, pidl, SHGDN_INFOLDER|SHGDN_FORPARSING, lpstrTemp );
2745
2746           if (! IsPidlFolder(fodInfos->Shell.FOIShellFolder, pidl)) /* Ignore folders */
2747           {
2748             if ( nFiles > 1)
2749             {
2750               *lpstrCurrFile++ =  '\"';
2751               strcpy( lpstrCurrFile, lpstrTemp );
2752               lpstrCurrFile += strlen( lpstrTemp );
2753               strcpy( lpstrCurrFile, "\" " );
2754               lpstrCurrFile += 2;
2755             }
2756             else
2757             {
2758               strcpy( lpstrAllFile, lpstrTemp );
2759             }
2760           }
2761           COMDLG32_SHFree( (LPVOID) pidl );
2762         }
2763       }
2764       SetWindowTextA( fodInfos->DlgInfos.hwndFileName, lpstrAllFile );
2765     }
2766     HeapFree(GetProcessHeap(),0, lpstrAllFile );
2767 }
2768
2769
2770 /* copied from shell32 to avoid linking to it */
2771 static HRESULT COMDLG32_StrRetToStrNA (LPVOID dest, DWORD len, LPSTRRET src, LPITEMIDLIST pidl)
2772 {
2773         switch (src->uType)
2774         {
2775           case STRRET_WSTR:
2776             WideCharToMultiByte(CP_ACP, 0, src->u.pOleStr, -1, (LPSTR)dest, len, NULL, NULL);
2777             COMDLG32_SHFree(src->u.pOleStr);
2778             break;
2779
2780           case STRRET_CSTR:
2781             lstrcpynA((LPSTR)dest, src->u.cStr, len);
2782             break;
2783
2784           case STRRET_OFFSET:
2785             lstrcpynA((LPSTR)dest, ((LPCSTR)&pidl->mkid)+src->u.uOffset, len);
2786             break;
2787
2788           default:
2789             FIXME("unknown type!\n");
2790             if (len)
2791             {
2792               *(LPSTR)dest = '\0';
2793             }
2794             return(FALSE);
2795         }
2796         return S_OK;
2797 }
2798
2799 /***********************************************************************
2800  * FILEDLG95_FILENAME_GetFileNames
2801  *
2802  * copies the filenames to a 0-delimited string list (A\0B\0C\0\0)
2803  */
2804 int FILEDLG95_FILENAME_GetFileNames (HWND hwnd, LPWSTR * lpstrFileList, UINT * sizeUsed)
2805 {
2806         FileOpenDlgInfos *fodInfos  = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
2807         UINT nStrCharCount = 0; /* index in src buffer */
2808         UINT nFileIndex = 0;    /* index in dest buffer */
2809         UINT nFileCount = 0;    /* number of files */
2810         UINT nStrLen = 0;       /* length of string in edit control */
2811         LPWSTR lpstrEdit;       /* buffer for string from edit control */
2812
2813         TRACE("\n");
2814
2815         /* get the filenames from the edit control */
2816         nStrLen = SendMessageW(fodInfos->DlgInfos.hwndFileName, WM_GETTEXTLENGTH, 0, 0);
2817         lpstrEdit = MemAlloc( (nStrLen+1)*sizeof(WCHAR) );
2818         GetDlgItemTextW(hwnd, IDC_FILENAME, lpstrEdit, nStrLen+1);
2819
2820         TRACE("nStrLen=%u str=%s\n", nStrLen, debugstr_w(lpstrEdit));
2821
2822         /* we might get single filename without any '"',
2823          * so we need nStrLen + terminating \0 + end-of-list \0 */
2824         *lpstrFileList = MemAlloc( (nStrLen+2)*sizeof(WCHAR) );
2825         *sizeUsed = 0;
2826
2827         /* build 0-delimited file list from filenames */
2828         while ( nStrCharCount <= nStrLen )
2829         {
2830           if ( lpstrEdit[nStrCharCount]=='"' )
2831           {
2832             nStrCharCount++;
2833             while ((lpstrEdit[nStrCharCount]!='"') && (nStrCharCount <= nStrLen))
2834             {
2835               (*lpstrFileList)[nFileIndex++] = lpstrEdit[nStrCharCount];
2836               (*sizeUsed)++;
2837               nStrCharCount++;
2838             }
2839             (*lpstrFileList)[nFileIndex++] = '\0';
2840             (*sizeUsed)++;
2841             nFileCount++;
2842           }
2843           nStrCharCount++;
2844         }
2845
2846         /* single, unquoted string */
2847         if ((nStrLen > 0) && (*sizeUsed == 0) )
2848         {
2849           strcpyW(*lpstrFileList, lpstrEdit);
2850           nFileIndex = strlenW(lpstrEdit) + 1;
2851           (*sizeUsed) = nFileIndex;
2852           nFileCount = 1;
2853         }
2854
2855         /* trailing \0 */
2856         (*lpstrFileList)[nFileIndex] = '\0';
2857         (*sizeUsed)++;
2858
2859         MemFree(lpstrEdit);
2860         return nFileCount;
2861 }
2862
2863 #define SETDefFormatEtc(fe,cf,med) \
2864 { \
2865     (fe).cfFormat = cf;\
2866     (fe).dwAspect = DVASPECT_CONTENT; \
2867     (fe).ptd =NULL;\
2868     (fe).tymed = med;\
2869     (fe).lindex = -1;\
2870 };
2871
2872 /*
2873  * DATAOBJECT Helper functions
2874  */
2875
2876 /***********************************************************************
2877  * COMCTL32_ReleaseStgMedium
2878  *
2879  * like ReleaseStgMedium from ole32
2880  */
2881 static void COMCTL32_ReleaseStgMedium (STGMEDIUM medium)
2882 {
2883       if(medium.pUnkForRelease)
2884       {
2885         IUnknown_Release(medium.pUnkForRelease);
2886       }
2887       else
2888       {
2889         GlobalUnlock(medium.u.hGlobal);
2890         GlobalFree(medium.u.hGlobal);
2891       }
2892 }
2893
2894 /***********************************************************************
2895  *          GetPidlFromDataObject
2896  *
2897  * Return pidl(s) by number from the cached DataObject
2898  *
2899  * nPidlIndex=0 gets the fully qualified root path
2900  */
2901 LPITEMIDLIST GetPidlFromDataObject ( IDataObject *doSelected, UINT nPidlIndex)
2902 {
2903
2904     STGMEDIUM medium;
2905     FORMATETC formatetc;
2906     LPITEMIDLIST pidl = NULL;
2907
2908     TRACE("sv=%p index=%u\n", doSelected, nPidlIndex);
2909
2910     /* Set the FORMATETC structure*/
2911     SETDefFormatEtc(formatetc, RegisterClipboardFormatA(CFSTR_SHELLIDLIST), TYMED_HGLOBAL);
2912
2913     /* Get the pidls from IDataObject */
2914     if(SUCCEEDED(IDataObject_GetData(doSelected,&formatetc,&medium)))
2915     {
2916       LPIDA cida = GlobalLock(medium.u.hGlobal);
2917       if(nPidlIndex <= cida->cidl)
2918       {
2919         pidl = COMDLG32_PIDL_ILClone((LPITEMIDLIST)(&((LPBYTE)cida)[cida->aoffset[nPidlIndex]]));
2920       }
2921       COMCTL32_ReleaseStgMedium(medium);
2922     }
2923     return pidl;
2924 }
2925
2926 /***********************************************************************
2927  *          GetNumSelected
2928  *
2929  * Return the number of selected items in the DataObject.
2930  *
2931 */
2932 UINT GetNumSelected( IDataObject *doSelected )
2933 {
2934     UINT retVal = 0;
2935     STGMEDIUM medium;
2936     FORMATETC formatetc;
2937
2938     TRACE("sv=%p\n", doSelected);
2939
2940     if (!doSelected) return 0;
2941
2942     /* Set the FORMATETC structure*/
2943     SETDefFormatEtc(formatetc, RegisterClipboardFormatA(CFSTR_SHELLIDLIST), TYMED_HGLOBAL);
2944
2945     /* Get the pidls from IDataObject */
2946     if(SUCCEEDED(IDataObject_GetData(doSelected,&formatetc,&medium)))
2947     {
2948       LPIDA cida = GlobalLock(medium.u.hGlobal);
2949       retVal = cida->cidl;
2950       COMCTL32_ReleaseStgMedium(medium);
2951       return retVal;
2952     }
2953     return 0;
2954 }
2955
2956 /*
2957  * TOOLS
2958  */
2959
2960 /***********************************************************************
2961  *      GetName
2962  *
2963  * Get the pidl's display name (relative to folder) and
2964  * put it in lpstrFileName.
2965  *
2966  * Return NOERROR on success,
2967  * E_FAIL otherwise
2968  */
2969
2970 HRESULT GetName(LPSHELLFOLDER lpsf, LPITEMIDLIST pidl,DWORD dwFlags,LPSTR lpstrFileName)
2971 {
2972   STRRET str;
2973   HRESULT hRes;
2974
2975   TRACE("sf=%p pidl=%p\n", lpsf, pidl);
2976
2977   if(!lpsf)
2978   {
2979     HRESULT hRes;
2980     SHGetDesktopFolder(&lpsf);
2981     hRes = GetName(lpsf,pidl,dwFlags,lpstrFileName);
2982     IShellFolder_Release(lpsf);
2983     return hRes;
2984   }
2985
2986   /* Get the display name of the pidl relative to the folder */
2987   if (SUCCEEDED(hRes = IShellFolder_GetDisplayNameOf(lpsf, pidl, dwFlags, &str)))
2988   {
2989       return COMDLG32_StrRetToStrNA(lpstrFileName, MAX_PATH, &str, pidl);
2990   }
2991   return E_FAIL;
2992 }
2993
2994 /***********************************************************************
2995  *      GetShellFolderFromPidl
2996  *
2997  * pidlRel is the item pidl relative
2998  * Return the IShellFolder of the absolute pidl
2999  */
3000 IShellFolder *GetShellFolderFromPidl(LPITEMIDLIST pidlAbs)
3001 {
3002   IShellFolder *psf = NULL,*psfParent;
3003
3004   TRACE("%p\n", pidlAbs);
3005
3006   if(SUCCEEDED(SHGetDesktopFolder(&psfParent)))
3007   {
3008     psf = psfParent;
3009     if(pidlAbs && pidlAbs->mkid.cb)
3010     {
3011       if(SUCCEEDED(IShellFolder_BindToObject(psfParent, pidlAbs, NULL, &IID_IShellFolder, (LPVOID*)&psf)))
3012       {
3013         IShellFolder_Release(psfParent);
3014         return psf;
3015       }
3016     }
3017     /* return the desktop */
3018     return psfParent;
3019   }
3020   return NULL;
3021 }
3022
3023 /***********************************************************************
3024  *      GetParentPidl
3025  *
3026  * Return the LPITEMIDLIST to the parent of the pidl in the list
3027  */
3028 LPITEMIDLIST GetParentPidl(LPITEMIDLIST pidl)
3029 {
3030   LPITEMIDLIST pidlParent;
3031
3032   TRACE("%p\n", pidl);
3033
3034   pidlParent = COMDLG32_PIDL_ILClone(pidl);
3035   COMDLG32_PIDL_ILRemoveLastID(pidlParent);
3036
3037   return pidlParent;
3038 }
3039
3040 /***********************************************************************
3041  *      GetPidlFromName
3042  *
3043  * returns the pidl of the file name relative to folder
3044  * NULL if an error occurred
3045  */
3046 LPITEMIDLIST GetPidlFromName(IShellFolder *lpsf,LPWSTR lpcstrFileName)
3047 {
3048   LPITEMIDLIST pidl = NULL;
3049   ULONG ulEaten;
3050
3051   TRACE("sf=%p file=%s\n", lpsf, debugstr_w(lpcstrFileName));
3052
3053   if(!lpcstrFileName) return NULL;
3054   if(!*lpcstrFileName) return NULL;
3055
3056   if(!lpsf)
3057   {
3058     if (SUCCEEDED(SHGetDesktopFolder(&lpsf))) {
3059         IShellFolder_ParseDisplayName(lpsf, 0, NULL, lpcstrFileName, &ulEaten, &pidl, NULL);
3060         IShellFolder_Release(lpsf);
3061     }
3062   }
3063   else
3064   {
3065     IShellFolder_ParseDisplayName(lpsf, 0, NULL, lpcstrFileName, &ulEaten, &pidl, NULL);
3066   }
3067   return pidl;
3068 }
3069
3070 /*
3071 */
3072 BOOL IsPidlFolder (LPSHELLFOLDER psf, LPITEMIDLIST pidl)
3073 {
3074         ULONG uAttr  = SFGAO_FOLDER | SFGAO_HASSUBFOLDER;
3075         HRESULT ret;
3076
3077         TRACE("%p, %p\n", psf, pidl);
3078
3079         ret = IShellFolder_GetAttributesOf( psf, 1, &pidl, &uAttr );
3080
3081         TRACE("-- 0x%08lx 0x%08lx\n", uAttr, ret);
3082         /* see documentation shell 4.1*/
3083         return uAttr & (SFGAO_FOLDER | SFGAO_HASSUBFOLDER);
3084 }
3085
3086 /***********************************************************************
3087  *      BrowseSelectedFolder
3088  */
3089 static BOOL BrowseSelectedFolder(HWND hwnd)
3090 {
3091   BOOL bBrowseSelFolder = FALSE;
3092   FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) GetPropA(hwnd,FileOpenDlgInfosStr);
3093
3094   TRACE("\n");
3095
3096   if (GetNumSelected(fodInfos->Shell.FOIDataObject) == 1)
3097   {
3098       LPITEMIDLIST pidlSelection;
3099
3100       /* get the file selected */
3101       pidlSelection  = GetPidlFromDataObject( fodInfos->Shell.FOIDataObject, 1);
3102       if (IsPidlFolder (fodInfos->Shell.FOIShellFolder, pidlSelection))
3103       {
3104           if ( FAILED( IShellBrowser_BrowseObject( fodInfos->Shell.FOIShellBrowser,
3105                          pidlSelection, SBSP_RELATIVE ) ) )
3106           {
3107                WCHAR notexist[] = {'P','a','t','h',' ','d','o','e','s',
3108                                    ' ','n','o','t',' ','e','x','i','s','t',0};
3109                MessageBoxW( hwnd, notexist, fodInfos->title, MB_OK | MB_ICONEXCLAMATION );
3110           }
3111
3112          bBrowseSelFolder = TRUE;
3113       }
3114       COMDLG32_SHFree( pidlSelection );
3115   }
3116
3117   return bBrowseSelFolder;
3118 }
3119
3120 /*
3121  * Memory allocation methods */
3122 static void *MemAlloc(UINT size)
3123 {
3124     return HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,size);
3125 }
3126
3127 static void MemFree(void *mem)
3128 {
3129     if(mem)
3130     {
3131         HeapFree(GetProcessHeap(),0,mem);
3132     }
3133 }