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