filedlg.c 136 KB
Newer Older
1
/*
2
 * COMMDLG - File Open Dialogs Win95 look and feel
3
 *
4 5
 * Copyright 1999 Francois Boisvert
 * Copyright 1999, 2000 Juergen Schmied
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 *
 * FIXME: The whole concept of handling unicode is badly broken.
 *	many hook-messages expect a pointer to a
 *	OPENFILENAMEA or W structure. With the current architecture
 *	we would have to convert the beast at every call to a hook.
 *	we have to find a better solution but it would likely cause
 *	a complete rewrite after which we should handle the
 *	OPENFILENAME structure without any converting (jsch).
 *
 * FIXME: any hook gets a OPENFILENAMEA structure
 *
 * FIXME: CDN_FILEOK is wrong implemented, other CDN_ messages likely too
 *
 * FIXME: old style hook messages are not implemented (except FILEOKSTRING)
 *
 * FIXME: algorithm for selecting the initial directory is too simple
 *
 * FIXME: add to recent docs
 *
39
 * FIXME: flags not implemented: OFN_DONTADDTORECENT,
40
 * OFN_NODEREFERENCELINKS, OFN_NOREADONLYRETURN,
41
 * OFN_NOTESTFILECREATE, OFN_USEMONIKERS
42 43 44 45
 *
 * FIXME: lCustData for lpfnHook (WM_INITDIALOG)
 *
 *
46
 */
47

48 49
#include <ctype.h>
#include <stdlib.h>
50
#include <stdarg.h>
51
#include <stdio.h>
52
#include <string.h>
53

54
#define COBJMACROS
55
#define NONAMELESSUNION
56

57
#include "windef.h"
58
#include "winbase.h"
59
#include "winternl.h"
60
#include "winnls.h"
61
#include "wingdi.h"
62
#include "winreg.h"
63
#include "winuser.h"
64
#include "commdlg.h"
65 66
#include "dlgs.h"
#include "cdlg.h"
67
#include "cderr.h"
68 69 70 71 72
#include "shellapi.h"
#include "shlobj.h"
#include "filedlgbrowser.h"
#include "shlwapi.h"

73
#include "wine/debug.h"
74
#include "wine/heap.h"
75

76 77 78
WINE_DEFAULT_DEBUG_CHANNEL(commdlg);

#define UNIMPLEMENTED_FLAGS \
79
(OFN_DONTADDTORECENT |\
80
OFN_NODEREFERENCELINKS | OFN_NOREADONLYRETURN |\
81
OFN_NOTESTFILECREATE /*| OFN_USEMONIKERS*/)
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

/***********************************************************************
 * Data structure and global variables
 */
typedef struct SFolder
{
  int m_iImageIndex;    /* Index of picture in image list */
  HIMAGELIST hImgList;
  int m_iIndent;      /* Indentation index */
  LPITEMIDLIST pidlItem;  /* absolute pidl of the item */

} SFOLDER,*LPSFOLDER;

typedef struct tagLookInInfo
{
  int iMaxIndentation;
  UINT uSelectedItem;
} LookInInfos;


/***********************************************************************
 * Defines and global variables
 */

/* Draw item constant */
#define XTEXTOFFSET 3

/* AddItem flags*/
#define LISTEND -1

/* SearchItem methods */
#define SEARCH_PIDL 1
#define SEARCH_EXP  2
#define ITEM_NOTFOUND -1

/* Undefined windows message sent by CreateViewObject*/
#define WM_GETISHELLBROWSER  WM_USER+7

120 121 122 123 124
#define TBPLACES_CMDID_PLACE0    0xa064
#define TBPLACES_CMDID_PLACE1    0xa065
#define TBPLACES_CMDID_PLACE2    0xa066
#define TBPLACES_CMDID_PLACE3    0xa067
#define TBPLACES_CMDID_PLACE4    0xa068
125

126 127 128 129 130 131 132
/* NOTE
 * Those macros exist in windowsx.h. However, you can't really use them since
 * they rely on the UNICODE defines and can't be used inside Wine itself.
 */

/* Combo box macros */
#define CBGetItemDataPtr(hwnd,iItemId) \
133
    SendMessageW(hwnd, CB_GETITEMDATA, (WPARAM)(iItemId), 0)
134

135
static const char LookInInfosStr[] = "LookInInfos"; /* LOOKIN combo box property */
136
static SIZE MemDialogSize = { 0, 0}; /* keep size of the (resizable) dialog */
137

138 139
FileOpenDlgInfos *get_filedlg_infoptr(HWND hwnd)
{
140
    return GetPropW(hwnd, L"FileOpenDlgInfos");
141 142
}

143 144 145 146 147
static BOOL is_dialog_hooked(const FileOpenDlgInfos *info)
{
    return (info->ofnInfos->Flags & OFN_ENABLEHOOK) && info->ofnInfos->lpfnHook;
}

148 149 150 151 152
static BOOL filedialog_is_readonly_hidden(const FileOpenDlgInfos *info)
{
    return (info->ofnInfos->Flags & OFN_HIDEREADONLY) || (info->DlgInfos.dwDlgProp & FODPROP_SAVEDLG);
}

153 154 155 156 157
/***********************************************************************
 * Prototypes
 */

/* Internal functions used by the dialog */
158
static LRESULT FILEDLG95_ResizeControls(HWND hwnd, WPARAM wParam, LPARAM lParam);
159
static LRESULT FILEDLG95_FillControls(HWND hwnd, WPARAM wParam, LPARAM lParam);
160
static LRESULT FILEDLG95_OnWMCommand(HWND hwnd, WPARAM wParam);
161
static LRESULT FILEDLG95_OnWMGetIShellBrowser(HWND hwnd);
162
static BOOL    FILEDLG95_OnOpen(HWND hwnd);
163 164 165 166 167 168 169 170 171
static LRESULT FILEDLG95_InitControls(HWND hwnd);
static void    FILEDLG95_Clean(HWND hwnd);

/* Functions used by the shell navigation */
static LRESULT FILEDLG95_SHELL_Init(HWND hwnd);
static BOOL    FILEDLG95_SHELL_UpFolder(HWND hwnd);
static BOOL    FILEDLG95_SHELL_ExecuteCommand(HWND hwnd, LPCSTR lpVerb);
static void    FILEDLG95_SHELL_Clean(HWND hwnd);

172
/* Functions used by the EDIT box */
173
static int FILEDLG95_FILENAME_GetFileNames (HWND hwnd, LPWSTR * lpstrFileList, UINT * sizeUsed);
174

175 176 177 178 179 180 181
/* Functions used by the filetype combo box */
static HRESULT FILEDLG95_FILETYPE_Init(HWND hwnd);
static BOOL    FILEDLG95_FILETYPE_OnCommand(HWND hwnd, WORD wNotifyCode);
static int     FILEDLG95_FILETYPE_SearchExt(HWND hwnd,LPCWSTR lpstrExt);
static void    FILEDLG95_FILETYPE_Clean(HWND hwnd);

/* Functions used by the Look In combo box */
182
static void    FILEDLG95_LOOKIN_Init(HWND hwndCombo);
183 184 185 186 187 188 189 190 191
static LRESULT FILEDLG95_LOOKIN_DrawItem(LPDRAWITEMSTRUCT pDIStruct);
static BOOL    FILEDLG95_LOOKIN_OnCommand(HWND hwnd, WORD wNotifyCode);
static int     FILEDLG95_LOOKIN_AddItem(HWND hwnd,LPITEMIDLIST pidl, int iInsertId);
static int     FILEDLG95_LOOKIN_SearchItem(HWND hwnd,WPARAM searchArg,int iSearchMethod);
static int     FILEDLG95_LOOKIN_InsertItemAfterParent(HWND hwnd,LPITEMIDLIST pidl);
static int     FILEDLG95_LOOKIN_RemoveMostExpandedItem(HWND hwnd);
       int     FILEDLG95_LOOKIN_SelectItem(HWND hwnd,LPITEMIDLIST pidl);
static void    FILEDLG95_LOOKIN_Clean(HWND hwnd);

192 193 194 195 196
/* Functions for dealing with the most-recently-used registry keys */
static void FILEDLG95_MRU_load_filename(LPWSTR stored_path);
static WCHAR FILEDLG95_MRU_get_slot(LPCWSTR module_name, LPWSTR stored_path, PHKEY hkey_ret);
static void FILEDLG95_MRU_save_filename(LPCWSTR filename);

197
/* Miscellaneous tool functions */
198
static HRESULT GetName(LPSHELLFOLDER lpsf, LPITEMIDLIST pidl,DWORD dwFlags,LPWSTR lpstrFileName);
199 200
IShellFolder* GetShellFolderFromPidl(LPITEMIDLIST pidlAbs);
LPITEMIDLIST  GetParentPidl(LPITEMIDLIST pidl);
201
static LPITEMIDLIST GetPidlFromName(IShellFolder *psf,LPWSTR lpcstrFileName);
202 203
static BOOL IsPidlFolder (LPSHELLFOLDER psf, LPCITEMIDLIST pidl);
static UINT GetNumSelected( IDataObject *doSelected );
204
static void COMCTL32_ReleaseStgMedium(STGMEDIUM medium);
205

206
static INT_PTR CALLBACK FileOpenDlgProc95(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
207 208
static INT_PTR FILEDLG95_HandleCustomDialogMessages(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static BOOL FILEDLG95_OnOpenMultipleFiles(HWND hwnd, LPWSTR lpstrFileList, UINT nFileCount, UINT sizeUsed);
209 210
static BOOL BrowseSelectedFolder(HWND hwnd);

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
static BOOL get_config_key_as_dword(HKEY hkey, const WCHAR *name, DWORD *value)
{
    DWORD type, data, size;

    size = sizeof(data);
    if (hkey && !RegQueryValueExW(hkey, name, 0, &type, (BYTE *)&data, &size))
    {
        *value = data;
        return TRUE;
    }

    return FALSE;
}

static BOOL get_config_key_dword(HKEY hkey, const WCHAR *name, DWORD *value)
{
    DWORD type, data, size;

    size = sizeof(data);
    if (hkey && !RegQueryValueExW(hkey, name, 0, &type, (BYTE *)&data, &size) && type == REG_DWORD)
    {
        *value = data;
        return TRUE;
    }

    return FALSE;
}

static BOOL get_config_key_string(HKEY hkey, const WCHAR *name, WCHAR **value)
{
    DWORD type, size;
    WCHAR *str;

244 245 246 247
    if (RegQueryValueExW(hkey, name, 0, &type, NULL, &size))
        return FALSE;
    if (type != REG_SZ && type != REG_EXPAND_SZ)
        return FALSE;
248 249 250 251 252 253 254 255 256 257 258 259

    str = heap_alloc(size);
    if (RegQueryValueExW(hkey, name, 0, &type, (BYTE *)str, &size))
    {
        heap_free(str);
        return FALSE;
    }

    *value = str;
    return TRUE;
}

260 261
static BOOL is_places_bar_enabled(const FileOpenDlgInfos *fodInfos)
{
262 263 264 265 266 267 268 269 270 271 272 273 274 275
    DWORD value;
    HKEY hkey;

    if (fodInfos->ofnInfos->lStructSize != sizeof(*fodInfos->ofnInfos) ||
            (fodInfos->ofnInfos->FlagsEx & OFN_EX_NOPLACESBAR) ||
           !(fodInfos->ofnInfos->Flags & OFN_EXPLORER))
    {
        return FALSE;
    }

    if (RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Comdlg32", &hkey))
        return TRUE;

    value = 0;
276
    get_config_key_as_dword(hkey, L"NoPlacesBar", &value);
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    RegCloseKey(hkey);
    return value == 0;
}

static void filedlg_collect_places_pidls(FileOpenDlgInfos *fodInfos)
{
    static const int default_places[] =
    {
        CSIDL_DESKTOP,
        CSIDL_MYDOCUMENTS,
        CSIDL_DRIVES,
    };
    unsigned int i;
    HKEY hkey;

    if (!RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Comdlg32\\Placesbar",
            &hkey))
    {
        for (i = 0; i < ARRAY_SIZE(fodInfos->places); i++)
        {
            WCHAR nameW[8];
            DWORD value;
299
            HRESULT hr;
300 301
            WCHAR *str;

302
            swprintf(nameW, ARRAY_SIZE(nameW), L"Place%d", i);
303
            if (get_config_key_dword(hkey, nameW, &value))
304 305 306 307 308
            {
                hr = SHGetSpecialFolderLocation(NULL, value, &fodInfos->places[i]);
                if (FAILED(hr))
                    WARN("Unrecognized special folder %u.\n", value);
            }
309 310
            else if (get_config_key_string(hkey, nameW, &str))
            {
311 312 313
                hr = SHParseDisplayName(str, NULL, &fodInfos->places[i], 0, NULL);
                if (FAILED(hr))
                    WARN("Failed to parse custom places location, %s.\n", debugstr_w(str));
314 315 316 317 318 319 320 321 322 323 324 325
                heap_free(str);
            }
        }

        /* FIXME: eliminate duplicates. */

        RegCloseKey(hkey);
        return;
    }

    for (i = 0; i < ARRAY_SIZE(default_places); i++)
        SHGetSpecialFolderLocation(NULL, default_places[i], &fodInfos->places[i]);
326 327
}

328 329 330 331 332 333 334 335 336 337
/***********************************************************************
 *      GetFileName95
 *
 * Creates an Open common dialog box that lets the user select
 * the drive, directory, and the name of a file or set of files to open.
 *
 * IN  : The FileOpenDlgInfos structure associated with the dialog
 * OUT : TRUE on success
 *       FALSE on cancel, error, close or filename-does-not-fit-in-buffer.
 */
338
static BOOL GetFileName95(FileOpenDlgInfos *fodInfos)
339 340
{
    LRESULT lRes;
341
    void *template;
342 343
    HRSRC hRes;
    HANDLE hDlgTmpl = 0;
344
    WORD templateid;
345 346 347 348

    /* test for missing functionality */
    if (fodInfos->ofnInfos->Flags & UNIMPLEMENTED_FLAGS)
    {
349
      FIXME("Flags 0x%08x not yet implemented\n",
350 351 352 353 354
         fodInfos->ofnInfos->Flags & UNIMPLEMENTED_FLAGS);
    }

    /* Create the dialog from a template */

355 356 357 358 359 360
    if (is_places_bar_enabled(fodInfos))
        templateid = NEWFILEOPENV2ORD;
    else
        templateid = NEWFILEOPENORD;

    if (!(hRes = FindResourceW(COMDLG32_hInstance, MAKEINTRESOURCEW(templateid), (LPCWSTR)RT_DIALOG)))
361 362 363 364
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_FINDRESFAILURE);
        return FALSE;
    }
365 366
    if (!(hDlgTmpl = LoadResource(COMDLG32_hInstance, hRes )) ||
        !(template = LockResource( hDlgTmpl )))
367 368 369 370 371
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
        return FALSE;
    }

372 373
    /* msdn: explorer style dialogs permit sizing by default.
     * The OFN_ENABLESIZING flag is only needed when a hook or
374
     * custom template is provided */
375 376 377 378
    if( (fodInfos->ofnInfos->Flags & OFN_EXPLORER) &&
            !(fodInfos->ofnInfos->Flags & ( OFN_ENABLEHOOK | OFN_ENABLETEMPLATE | OFN_ENABLETEMPLATEHANDLE)))
        fodInfos->ofnInfos->Flags |= OFN_ENABLESIZING;

379 380 381 382 383 384
    if (fodInfos->ofnInfos->Flags & OFN_ENABLESIZING)
    {
        fodInfos->sizedlg.cx = fodInfos->sizedlg.cy = 0;
        fodInfos->initial_size.x = fodInfos->initial_size.y = 0;
    }

385
    /* old style hook messages */
386
    if (is_dialog_hooked(fodInfos))
387
    {
388 389 390 391
      fodInfos->HookMsg.fileokstring = RegisterWindowMessageW(FILEOKSTRINGW);
      fodInfos->HookMsg.lbselchstring = RegisterWindowMessageW(LBSELCHSTRINGW);
      fodInfos->HookMsg.helpmsgstring = RegisterWindowMessageW(HELPMSGSTRINGW);
      fodInfos->HookMsg.sharevistring = RegisterWindowMessageW(SHAREVISTRINGW);
392 393
    }

394 395 396 397 398 399 400 401
    if (fodInfos->unicode)
      lRes = DialogBoxIndirectParamW(COMDLG32_hInstance,
                                     template,
                                     fodInfos->ofnInfos->hwndOwner,
                                     FileOpenDlgProc95,
                                     (LPARAM) fodInfos);
    else
      lRes = DialogBoxIndirectParamA(COMDLG32_hInstance,
402
                                     template,
403 404 405
                                     fodInfos->ofnInfos->hwndOwner,
                                     FileOpenDlgProc95,
                                     (LPARAM) fodInfos);
406
    if (fodInfos->ole_initialized)
407
        OleUninitialize();
408 409 410 411 412 413 414 415

    /* Unable to create the dialog */
    if( lRes == -1)
        return FALSE;

    return lRes;
}

416
static WCHAR *heap_strdupAtoW(const char *str)
417
{
418 419
    WCHAR *ret;
    INT len;
420

421 422
    if (!str)
        return NULL;
423

424
    len = MultiByteToWideChar(CP_ACP, 0, str, -1, 0, 0);
425
    ret = heap_alloc(len * sizeof(WCHAR));
426
    MultiByteToWideChar(CP_ACP, 0, str, -1, ret, len);
427

428 429
    return ret;
}
430

431 432 433
static void init_filedlg_infoW(OPENFILENAMEW *ofn, FileOpenDlgInfos *info)
{
    INITCOMMONCONTROLSEX icc;
434

435 436 437 438
    /* Initialize ComboBoxEx32 */
    icc.dwSize = sizeof(icc);
    icc.dwICC = ICC_USEREX_CLASSES;
    InitCommonControlsEx(&icc);
439

440 441
    /* Initialize CommDlgExtendedError() */
    COMDLG32_SetCommDlgExtendedError(0);
442

443
    memset(info, 0, sizeof(*info));
444

445 446
    /* Pass in the original ofn */
    info->ofnInfos = ofn;
447

448 449 450 451
    info->title = ofn->lpstrTitle;
    info->defext = ofn->lpstrDefExt;
    info->filter = ofn->lpstrFilter;
    info->customfilter = ofn->lpstrCustomFilter;
452

453 454
    if (ofn->lpstrFile)
    {
455
        info->filename = heap_alloc(ofn->nMaxFile * sizeof(WCHAR));
456 457
        lstrcpynW(info->filename, ofn->lpstrFile, ofn->nMaxFile);
    }
458

459 460 461 462 463
    if (ofn->lpstrInitialDir)
    {
        DWORD len = ExpandEnvironmentStringsW(ofn->lpstrInitialDir, NULL, 0);
        if (len)
        {
464
            info->initdir = heap_alloc(len * sizeof(WCHAR));
465 466 467
            ExpandEnvironmentStringsW(ofn->lpstrInitialDir, info->initdir, len);
        }
    }
468

469
    info->unicode = TRUE;
470 471
}

472
static void init_filedlg_infoA(OPENFILENAMEA *ofn, FileOpenDlgInfos *info)
473
{
474
    OPENFILENAMEW ofnW;
475
    int len;
476

477
    ofnW = *(OPENFILENAMEW *)ofn;
478

479 480 481
    ofnW.lpstrInitialDir = heap_strdupAtoW(ofn->lpstrInitialDir);
    ofnW.lpstrDefExt = heap_strdupAtoW(ofn->lpstrDefExt);
    ofnW.lpstrTitle = heap_strdupAtoW(ofn->lpstrTitle);
482

483 484 485
    if (ofn->lpstrFile)
    {
        len = MultiByteToWideChar(CP_ACP, 0, ofn->lpstrFile, ofn->nMaxFile, NULL, 0);
486
        ofnW.lpstrFile = heap_alloc(len * sizeof(WCHAR));
487 488 489 490
        MultiByteToWideChar(CP_ACP, 0, ofn->lpstrFile, ofn->nMaxFile, ofnW.lpstrFile, len);
        ofnW.nMaxFile = len;
    }

491 492 493
    if (ofn->lpstrFilter)
    {
        LPCSTR s;
494
        int n;
495 496 497 498 499 500 501

        /* filter is a list...  title\0ext\0......\0\0 */
        s = ofn->lpstrFilter;
        while (*s) s = s+strlen(s)+1;
        s++;
        n = s - ofn->lpstrFilter;
        len = MultiByteToWideChar(CP_ACP, 0, ofn->lpstrFilter, n, NULL, 0);
502
        ofnW.lpstrFilter = heap_alloc(len * sizeof(WCHAR));
503 504
        MultiByteToWideChar(CP_ACP, 0, ofn->lpstrFilter, n, (WCHAR *)ofnW.lpstrFilter, len);
    }
505

506 507 508 509 510 511 512 513 514 515 516 517
    /* convert lpstrCustomFilter */
    if (ofn->lpstrCustomFilter)
    {
        int n, len;
        LPCSTR s;

        /* customfilter contains a pair of strings...  title\0ext\0 */
        s = ofn->lpstrCustomFilter;
        if (*s) s = s+strlen(s)+1;
        if (*s) s = s+strlen(s)+1;
        n = s - ofn->lpstrCustomFilter;
        len = MultiByteToWideChar(CP_ACP, 0, ofn->lpstrCustomFilter, n, NULL, 0);
518
        ofnW.lpstrCustomFilter = heap_alloc(len * sizeof(WCHAR));
519 520
        MultiByteToWideChar(CP_ACP, 0, ofn->lpstrCustomFilter, n, ofnW.lpstrCustomFilter, len);
    }
521

522
    init_filedlg_infoW(&ofnW, info);
523

524 525 526
    /* fixup A-specific fields */
    info->ofnInfos = (OPENFILENAMEW *)ofn;
    info->unicode = FALSE;
527

528
    /* free what was duplicated */
529 530
    heap_free((void *)ofnW.lpstrInitialDir);
    heap_free(ofnW.lpstrFile);
531 532 533 534 535 536 537 538 539 540
}

/***********************************************************************
 *      GetFileDialog95
 *
 * Call GetFileName95 with this structure and clean the memory.
 */
static BOOL GetFileDialog95(FileOpenDlgInfos *info, UINT dlg_type)
{
    WCHAR *current_dir = NULL;
541
    unsigned int i;
542 543 544 545
    BOOL ret;

    /* save current directory */
    if (info->ofnInfos->Flags & OFN_NOCHANGEDIR)
546
    {
547
        current_dir = heap_alloc(MAX_PATH * sizeof(WCHAR));
548
        GetCurrentDirectoryW(MAX_PATH, current_dir);
549
    }
550

551 552 553 554 555 556 557 558 559 560 561 562
    switch (dlg_type)
    {
    case OPEN_DIALOG:
        ret = GetFileName95(info);
        break;
    case SAVE_DIALOG:
        info->DlgInfos.dwDlgProp |= FODPROP_SAVEDLG;
        ret = GetFileName95(info);
        break;
    default:
        ret = FALSE;
    }
563

564 565 566
    if (current_dir)
    {
        SetCurrentDirectoryW(current_dir);
567
        heap_free(current_dir);
568
    }
569

570 571
    if (!info->unicode)
    {
572 573 574 575
        heap_free((void *)info->defext);
        heap_free((void *)info->title);
        heap_free((void *)info->filter);
        heap_free((void *)info->customfilter);
576
    }
577

578 579
    heap_free(info->filename);
    heap_free(info->initdir);
580 581 582 583

    for (i = 0; i < ARRAY_SIZE(info->places); i++)
        ILFree(info->places[i]);

584
    return ret;
585 586
}

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
/******************************************************************************
 * COMDLG32_GetDisplayNameOf [internal]
 *
 * Helper function to get the display name for a pidl.
 */
static BOOL COMDLG32_GetDisplayNameOf(LPCITEMIDLIST pidl, LPWSTR pwszPath) {
    LPSHELLFOLDER psfDesktop;
    STRRET strret;
        
    if (FAILED(SHGetDesktopFolder(&psfDesktop)))
        return FALSE;

    if (FAILED(IShellFolder_GetDisplayNameOf(psfDesktop, pidl, SHGDN_FORPARSING, &strret))) {
        IShellFolder_Release(psfDesktop);
        return FALSE;
    }

    IShellFolder_Release(psfDesktop);
    return SUCCEEDED(StrRetToBufW(&strret, pidl, pwszPath, MAX_PATH));
}

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
/******************************************************************************
 * COMDLG32_GetCanonicalPath [internal]
 *
 * Helper function to get the canonical path.
 */
void COMDLG32_GetCanonicalPath(PCIDLIST_ABSOLUTE pidlAbsCurrent,
                               LPWSTR lpstrFile, LPWSTR lpstrPathAndFile)
{
  WCHAR lpstrTemp[MAX_PATH];

  /* Get the current directory name */
  if (!COMDLG32_GetDisplayNameOf(pidlAbsCurrent, lpstrPathAndFile))
  {
    /* last fallback */
    GetCurrentDirectoryW(MAX_PATH, lpstrPathAndFile);
  }
  PathAddBackslashW(lpstrPathAndFile);

626
  TRACE("current directory=%s, file=%s\n", debugstr_w(lpstrPathAndFile), debugstr_w(lpstrFile));
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

  /* if the user specified a fully qualified path use it */
  if(PathIsRelativeW(lpstrFile))
  {
    lstrcatW(lpstrPathAndFile, lpstrFile);
  }
  else
  {
    /* does the path have a drive letter? */
    if (PathGetDriveNumberW(lpstrFile) == -1)
      lstrcpyW(lpstrPathAndFile+2, lpstrFile);
    else
      lstrcpyW(lpstrPathAndFile, lpstrFile);
  }

  /* resolve "." and ".." */
  PathCanonicalizeW(lpstrTemp, lpstrPathAndFile );
  lstrcpyW(lpstrPathAndFile, lpstrTemp);
  TRACE("canon=%s\n", debugstr_w(lpstrPathAndFile));
}

648 649 650 651 652 653 654 655 656 657 658 659 660
/***********************************************************************
 *      COMDLG32_SplitFileNames [internal]
 *
 * Creates a delimited list of filenames.
 */
int COMDLG32_SplitFileNames(LPWSTR lpstrEdit, UINT nStrLen, LPWSTR *lpstrFileList, UINT *sizeUsed)
{
	UINT nStrCharCount = 0;	/* index in src buffer */
	UINT nFileIndex = 0;	/* index in dest buffer */
	UINT nFileCount = 0;	/* number of files */

	/* we might get single filename without any '"',
	 * so we need nStrLen + terminating \0 + end-of-list \0 */
661
	*lpstrFileList = heap_alloc((nStrLen + 2) * sizeof(WCHAR));
662 663 664 665 666 667 668 669
	*sizeUsed = 0;

	/* build delimited file list from filenames */
	while ( nStrCharCount <= nStrLen )
	{
	  if ( lpstrEdit[nStrCharCount]=='"' )
	  {
	    nStrCharCount++;
670
	    while ((nStrCharCount <= nStrLen) && (lpstrEdit[nStrCharCount]!='"'))
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
	    {
	      (*lpstrFileList)[nFileIndex++] = lpstrEdit[nStrCharCount];
	      nStrCharCount++;
	    }
	    (*lpstrFileList)[nFileIndex++] = 0;
	    nFileCount++;
	  }
	  nStrCharCount++;
	}

	/* single, unquoted string */
	if ((nStrLen > 0) && (nFileIndex == 0) )
	{
	  lstrcpyW(*lpstrFileList, lpstrEdit);
	  nFileIndex = lstrlenW(lpstrEdit) + 1;
	  nFileCount = 1;
	}

        /* trailing \0 */
        (*lpstrFileList)[nFileIndex++] = '\0';

        *sizeUsed = nFileIndex;
	return nFileCount;
}

696 697 698
/***********************************************************************
 *      ArrangeCtrlPositions [internal]
 *
699
 * NOTE: Make sure to add testcases for any changes made here.
700 701 702 703 704
 */
static void ArrangeCtrlPositions(HWND hwndChildDlg, HWND hwndParentDlg, BOOL hide_help)
{
    HWND hwndChild, hwndStc32;
    RECT rectParent, rectChild, rectStc32;
705 706
    INT help_fixup = 0;
    int chgx, chgy;
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773

    /* Take into account if open as read only checkbox and help button
     * are hidden
     */
     if (hide_help)
     {
         RECT rectHelp, rectCancel;
         GetWindowRect(GetDlgItem(hwndParentDlg, pshHelp), &rectHelp);
         GetWindowRect(GetDlgItem(hwndParentDlg, IDCANCEL), &rectCancel);
         /* subtract the height of the help button plus the space between
          * the help button and the cancel button to the height of the dialog
          */
          help_fixup = rectHelp.bottom - rectCancel.bottom;
    }

    /*
      There are two possibilities to add components to the default file dialog box.

      By default, all the new components are added below the standard dialog box (the else case).

      However, if there is a static text component with the stc32 id, a special case happens.
      The x and y coordinates of stc32 indicate the top left corner where to place the standard file dialog box
      in the window and the cx and cy indicate how to size the window.
      Moreover, if the new component's coordinates are on the left of the stc32 , it is placed on the left 
      of the standard file dialog box. If they are above the stc32 component, it is placed above and so on....
      
     */

    GetClientRect(hwndParentDlg, &rectParent);

    /* when arranging controls we have to use fixed parent size */
    rectParent.bottom -= help_fixup;

    hwndStc32 = GetDlgItem(hwndChildDlg, stc32);
    if (hwndStc32)
    {
        GetWindowRect(hwndStc32, &rectStc32);
        MapWindowPoints(0, hwndChildDlg, (LPPOINT)&rectStc32, 2);

        /* set the size of the stc32 control according to the size of
         * client area of the parent dialog
         */
        SetWindowPos(hwndStc32, 0,
                     0, 0,
                     rectParent.right, rectParent.bottom,
                     SWP_NOMOVE | SWP_NOZORDER);
    }
    else
        SetRectEmpty(&rectStc32);

    /* this part moves controls of the child dialog */
    hwndChild = GetWindow(hwndChildDlg, GW_CHILD);
    while (hwndChild)
    {
        if (hwndChild != hwndStc32)
        {
            GetWindowRect(hwndChild, &rectChild);
            MapWindowPoints(0, hwndChildDlg, (LPPOINT)&rectChild, 2);

            /* move only if stc32 exist */
            if (hwndStc32 && rectChild.left > rectStc32.right)
            {
                /* move to the right of visible controls of the parent dialog */
                rectChild.left += rectParent.right;
                rectChild.left -= rectStc32.right;
            }
            /* move even if stc32 doesn't exist */
774
            if (rectChild.top >= rectStc32.bottom)
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
            {
                /* move below visible controls of the parent dialog */
                rectChild.top += rectParent.bottom;
                rectChild.top -= rectStc32.bottom - rectStc32.top;
            }

            SetWindowPos(hwndChild, 0, rectChild.left, rectChild.top,
                         0, 0, SWP_NOSIZE | SWP_NOZORDER);
        }
        hwndChild = GetWindow(hwndChild, GW_HWNDNEXT);
    }

    /* this part moves controls of the parent dialog */
    hwndChild = GetWindow(hwndParentDlg, GW_CHILD);
    while (hwndChild)
    {
        if (hwndChild != hwndChildDlg)
        {
            GetWindowRect(hwndChild, &rectChild);
            MapWindowPoints(0, hwndParentDlg, (LPPOINT)&rectChild, 2);

            /* left,top of stc32 marks the position of controls
             * from the parent dialog
             */
            rectChild.left += rectStc32.left;
            rectChild.top += rectStc32.top;

            SetWindowPos(hwndChild, 0, rectChild.left, rectChild.top,
                         0, 0, SWP_NOSIZE | SWP_NOZORDER);
        }
        hwndChild = GetWindow(hwndChild, GW_HWNDNEXT);
    }

    /* calculate the size of the resulting dialog */

    /* here we have to use original parent size */
    GetClientRect(hwndParentDlg, &rectParent);
    GetClientRect(hwndChildDlg, &rectChild);
813 814
    TRACE( "parent %s child %s stc32 %s\n", wine_dbgstr_rect( &rectParent),
            wine_dbgstr_rect( &rectChild), wine_dbgstr_rect( &rectStc32));
815 816 817

    if (hwndStc32)
    {
818 819 820
        /* width */
        if (rectParent.right > rectStc32.right - rectStc32.left)
            chgx = rectChild.right - ( rectStc32.right - rectStc32.left);
821
        else
822 823 824 825
            chgx = rectChild.right - rectParent.right;
        /* height */
        if (rectParent.bottom > rectStc32.bottom - rectStc32.top)
            chgy = rectChild.bottom - ( rectStc32.bottom - rectStc32.top) - help_fixup;
826
        else
827 828
            /* Unconditionally set new dialog
             * height to that of the child
829
             */
830
            chgy = rectChild.bottom - rectParent.bottom;
831 832 833
    }
    else
    {
834 835
        chgx = 0;
        chgy = rectChild.bottom - help_fixup;
836 837
    }
    /* set the size of the parent dialog */
838
    GetWindowRect(hwndParentDlg, &rectParent);
839 840
    SetWindowPos(hwndParentDlg, 0,
                 0, 0,
841 842
                 rectParent.right - rectParent.left + chgx,
                 rectParent.bottom - rectParent.top + chgy,
843 844 845
                 SWP_NOMOVE | SWP_NOZORDER);
}

Mike McCormack's avatar
Mike McCormack committed
846
static INT_PTR CALLBACK FileOpenDlgProcUserTemplate(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
847
{
848 849 850
    switch(uMsg) {
    case WM_INITDIALOG:
        return TRUE;
851
    }
852
    return FALSE;
853 854
}

Mike McCormack's avatar
Mike McCormack committed
855
static HWND CreateTemplateDialog(FileOpenDlgInfos *fodInfos, HWND hwnd)
856 857 858 859 860 861
{
    LPCVOID template;
    HRSRC hRes;
    HANDLE hDlgTmpl = 0;
    HWND hChildDlg = 0;

862
    TRACE("%p, %p\n", fodInfos, hwnd);
863 864 865 866 867 868 869 870 871 872 873

    /*
     * If OFN_ENABLETEMPLATEHANDLE is specified, the OPENFILENAME
     * structure's hInstance parameter is not a HINSTANCE, but
     * instead a pointer to a template resource to use.
     */
    if (fodInfos->ofnInfos->Flags & (OFN_ENABLETEMPLATE | OFN_ENABLETEMPLATEHANDLE))
    {
      HINSTANCE hinst;
      if (fodInfos->ofnInfos->Flags  & OFN_ENABLETEMPLATEHANDLE)
      {
874
        hinst = COMDLG32_hInstance;
875 876 877 878 879 880 881 882 883 884 885
        if( !(template = LockResource( fodInfos->ofnInfos->hInstance)))
        {
          COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
          return NULL;
        }
      }
      else
      {
        hinst = fodInfos->ofnInfos->hInstance;
        if(fodInfos->unicode)
        {
Jacek Caban's avatar
Jacek Caban committed
886
            LPOPENFILENAMEW ofn = fodInfos->ofnInfos;
887 888 889 890
            hRes = FindResourceW( hinst, ofn->lpTemplateName, (LPWSTR)RT_DIALOG);
        }
        else
        {
Jacek Caban's avatar
Jacek Caban committed
891
            LPOPENFILENAMEA ofn = (LPOPENFILENAMEA)fodInfos->ofnInfos;
892 893 894 895 896 897 898 899 900 901 902 903 904 905
            hRes = FindResourceA( hinst, ofn->lpTemplateName, (LPSTR)RT_DIALOG);
        }
        if (!hRes)
        {
          COMDLG32_SetCommDlgExtendedError(CDERR_FINDRESFAILURE);
          return NULL;
        }
        if (!(hDlgTmpl = LoadResource( hinst, hRes )) ||
            !(template = LockResource( hDlgTmpl )))
        {
          COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
          return NULL;
    	}
      }
906 907
      if (fodInfos->unicode)
          hChildDlg = CreateDialogIndirectParamW(hinst, template, hwnd,
908
              is_dialog_hooked(fodInfos) ? (DLGPROC)fodInfos->ofnInfos->lpfnHook : FileOpenDlgProcUserTemplate,
909 910 911
              (LPARAM)fodInfos->ofnInfos);
      else
          hChildDlg = CreateDialogIndirectParamA(hinst, template, hwnd,
912
              is_dialog_hooked(fodInfos) ? (DLGPROC)fodInfos->ofnInfos->lpfnHook : FileOpenDlgProcUserTemplate,
913
              (LPARAM)fodInfos->ofnInfos);
914
      return hChildDlg;
915
    }
916
    else if (is_dialog_hooked(fodInfos))
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
    {
      RECT rectHwnd;
      struct  {
         DLGTEMPLATE tmplate;
         WORD menu,class,title;
         } temp;
      GetClientRect(hwnd,&rectHwnd);
      temp.tmplate.style = WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | DS_CONTROL | DS_3DLOOK;
      temp.tmplate.dwExtendedStyle = 0;
      temp.tmplate.cdit = 0;
      temp.tmplate.x = 0;
      temp.tmplate.y = 0;
      temp.tmplate.cx = 0;
      temp.tmplate.cy = 0;
      temp.menu = temp.class = temp.title = 0;

      hChildDlg = CreateDialogIndirectParamA(COMDLG32_hInstance, &temp.tmplate,
934
                  hwnd, (DLGPROC)fodInfos->ofnInfos->lpfnHook, (LPARAM)fodInfos->ofnInfos);
935 936 937 938 939 940 941 942 943 944 945 946

      return hChildDlg;
    }
    return NULL;
}

/***********************************************************************
*          SendCustomDlgNotificationMessage
*
* Send CustomDialogNotification (CDN_FIRST -- CDN_LAST) message to the custom template dialog
*/

947
LRESULT SendCustomDlgNotificationMessage(HWND hwndParentDlg, UINT uCode)
948
{
949
    FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwndParentDlg);
950 951
    LRESULT hook_result;
    OFNOTIFYW ofnNotify;
952

953
    TRACE("%p %d\n", hwndParentDlg, uCode);
954

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    if (!fodInfos || !fodInfos->DlgInfos.hwndCustomDlg)
        return 0;

    TRACE("CALL NOTIFY for %d\n", uCode);

    ofnNotify.hdr.hwndFrom = hwndParentDlg;
    ofnNotify.hdr.idFrom = 0;
    ofnNotify.hdr.code = uCode;
    ofnNotify.lpOFN = fodInfos->ofnInfos;
    ofnNotify.pszFile = NULL;

    if (fodInfos->unicode)
        hook_result = SendMessageW(fodInfos->DlgInfos.hwndCustomDlg, WM_NOTIFY, 0, (LPARAM)&ofnNotify);
    else
        hook_result = SendMessageA(fodInfos->DlgInfos.hwndCustomDlg, WM_NOTIFY, 0, (LPARAM)&ofnNotify);

    TRACE("RET NOTIFY retval %#lx\n", hook_result);
972

973
    return hook_result;
974 975
}

976
static INT_PTR FILEDLG95_Handle_GetFilePath(HWND hwnd, DWORD size, LPVOID result)
977
{
978 979
    UINT len, total;
    WCHAR *p, *buffer;
980
    FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
981 982 983 984 985 986 987

    TRACE("CDM_GETFILEPATH:\n");

    if ( ! (fodInfos->ofnInfos->Flags & OFN_EXPLORER ) )
        return -1;

    /* get path and filenames */
988
    len = SendMessageW( fodInfos->DlgInfos.hwndFileName, WM_GETTEXTLENGTH, 0, 0 );
989
    buffer = heap_alloc( (len + 2 + MAX_PATH) * sizeof(WCHAR) );
990 991
    COMDLG32_GetDisplayNameOf( fodInfos->ShellInfos.pidlAbsCurrent, buffer );
    if (len)
992
    {
993
        p = buffer + lstrlenW(buffer);
994 995
        *p++ = '\\';
        SendMessageW( fodInfos->DlgInfos.hwndFileName, WM_GETTEXT, len + 1, (LPARAM)p );
996
    }
997
    if (fodInfos->unicode)
998
    {
999
        total = lstrlenW( buffer) + 1;
1000 1001
        if (result) lstrcpynW( result, buffer, size );
        TRACE( "CDM_GETFILEPATH: returning %u %s\n", total, debugstr_w(result));
1002 1003 1004
    }
    else
    {
1005 1006 1007
        total = WideCharToMultiByte( CP_ACP, 0, buffer, -1, NULL, 0, NULL, NULL );
        if (total <= size) WideCharToMultiByte( CP_ACP, 0, buffer, -1, result, size, NULL, NULL );
        TRACE( "CDM_GETFILEPATH: returning %u %s\n", total, debugstr_a(result));
1008
    }
1009
    heap_free( buffer );
1010
    return total;
1011 1012 1013 1014 1015 1016 1017
}

/***********************************************************************
*         FILEDLG95_HandleCustomDialogMessages
*
* Handle Custom Dialog Messages (CDM_FIRST -- CDM_LAST) messages
*/
1018
static INT_PTR FILEDLG95_HandleCustomDialogMessages(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1019
{
1020
    FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
1021
    WCHAR lpstrPath[MAX_PATH];
1022
    INT_PTR retval;
1023 1024

    if(!fodInfos) return FALSE;
1025 1026 1027 1028

    switch(uMsg)
    {
        case CDM_GETFILEPATH:
1029 1030
            retval = FILEDLG95_Handle_GetFilePath(hwnd, (UINT)wParam, (LPVOID)lParam);
            break;
1031 1032 1033

        case CDM_GETFOLDERPATH:
            TRACE("CDM_GETFOLDERPATH:\n");
1034 1035
            COMDLG32_GetDisplayNameOf(fodInfos->ShellInfos.pidlAbsCurrent, lpstrPath);
            if (lParam) 
1036
            {
1037 1038 1039 1040 1041 1042
                if (fodInfos->unicode)
                    lstrcpynW((LPWSTR)lParam, lpstrPath, (int)wParam);
                else
                    WideCharToMultiByte(CP_ACP, 0, lpstrPath, -1, 
                                        (LPSTR)lParam, (int)wParam, NULL, NULL);
            }        
1043
            retval = lstrlenW(lpstrPath) + 1;
1044
            break;
1045

1046
        case CDM_GETFOLDERIDLIST:
1047
            retval = ILGetSize(fodInfos->ShellInfos.pidlAbsCurrent);
1048 1049 1050 1051
            if (retval <= wParam)
                memcpy((void*)lParam, fodInfos->ShellInfos.pidlAbsCurrent, retval);
            break;

1052
        case CDM_GETSPEC:
1053 1054 1055 1056 1057 1058 1059 1060 1061
            TRACE("CDM_GETSPEC:\n");
            retval = SendMessageW(fodInfos->DlgInfos.hwndFileName, WM_GETTEXTLENGTH, 0, 0) + 1;
            if (lParam)
            {
                if (fodInfos->unicode)
                    SendMessageW(fodInfos->DlgInfos.hwndFileName, WM_GETTEXT, wParam, lParam);
                else
                    SendMessageA(fodInfos->DlgInfos.hwndFileName, WM_GETTEXT, wParam, lParam);
            }
1062
            break;
1063 1064 1065

        case CDM_SETCONTROLTEXT:
            TRACE("CDM_SETCONTROLTEXT:\n");
1066 1067 1068 1069 1070 1071 1072
	    if ( lParam )
            {
                if( fodInfos->unicode )
	            SetDlgItemTextW( hwnd, (UINT) wParam, (LPWSTR) lParam );
                else
	            SetDlgItemTextA( hwnd, (UINT) wParam, (LPSTR) lParam );
            }
1073 1074
            retval = TRUE;
            break;
1075 1076

        case CDM_HIDECONTROL:
1077 1078 1079 1080 1081 1082 1083 1084
            /* MSDN states that it should fail for not OFN_EXPLORER case */
            if (fodInfos->ofnInfos->Flags & OFN_EXPLORER)
            {
                HWND control = GetDlgItem( hwnd, wParam );
                if (control) ShowWindow( control, SW_HIDE );
                retval = TRUE;
            }
            else retval = FALSE;
1085 1086 1087
            break;

        default:
1088 1089
            if (uMsg >= CDM_FIRST && uMsg <= CDM_LAST)
                FIXME("message CDM_FIRST+%04x not implemented\n", uMsg - CDM_FIRST);
1090
            return FALSE;
1091
    }
1092
    SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, retval);
1093 1094 1095
    return TRUE;
}

1096 1097 1098 1099 1100 1101 1102
/***********************************************************************
 *          FILEDLG95_OnWMGetMMI
 *
 * WM_GETMINMAXINFO message handler for resizable dialogs
 */
static LRESULT FILEDLG95_OnWMGetMMI( HWND hwnd, LPMINMAXINFO mmiptr)
{
1103
    FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    if( !(fodInfos->ofnInfos->Flags & OFN_ENABLESIZING)) return FALSE;
    if( fodInfos->initial_size.x || fodInfos->initial_size.y)
    {
        mmiptr->ptMinTrackSize = fodInfos->initial_size;
    }
    return TRUE;
}

/***********************************************************************
 *          FILEDLG95_OnWMSize
 *
 * WM_SIZE message handler, resize the dialog. Re-arrange controls.
 *
 * FIXME: this could be made more elaborate. Now use a simple scheme
 * where the file view is enlarged and the controls are either moved
 * vertically or horizontally to get out of the way. Only the "grip"
 * is moved in both directions to stay in the corner.
 */
1122
static LRESULT FILEDLG95_OnWMSize(HWND hwnd, WPARAM wParam)
1123 1124 1125 1126 1127 1128 1129 1130
{
    RECT rc, rcview;
    int chgx, chgy;
    HWND ctrl;
    HDWP hdwp;
    FileOpenDlgInfos *fodInfos;

    if( wParam != SIZE_RESTORED) return FALSE;
1131
    fodInfos = get_filedlg_infoptr(hwnd);
1132 1133 1134
    if( !(fodInfos->ofnInfos->Flags & OFN_ENABLESIZING)) return FALSE;
    /* get the new dialog rectangle */
    GetWindowRect( hwnd, &rc);
1135
    TRACE("%p, size from %d,%d to %d,%d\n", hwnd, fodInfos->sizedlg.cx, fodInfos->sizedlg.cy,
1136
            rc.right -rc.left, rc.bottom -rc.top);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    /* not initialized yet */
    if( (fodInfos->sizedlg.cx == 0 && fodInfos->sizedlg.cy == 0) ||
        ((fodInfos->sizedlg.cx == rc.right -rc.left) && /* no change */
             (fodInfos->sizedlg.cy == rc.bottom -rc.top)))
        return FALSE;
    chgx = rc.right - rc.left - fodInfos->sizedlg.cx;
    chgy = rc.bottom - rc.top - fodInfos->sizedlg.cy;
    fodInfos->sizedlg.cx = rc.right - rc.left;
    fodInfos->sizedlg.cy = rc.bottom - rc.top;
    /* change the size of the view window */
    GetWindowRect( fodInfos->ShellInfos.hwndView, &rcview);
    MapWindowPoints( NULL, hwnd, (LPPOINT) &rcview, 2);
    hdwp = BeginDeferWindowPos( 10);
    DeferWindowPos( hdwp, fodInfos->ShellInfos.hwndView, NULL, 0, 0,
            rcview.right - rcview.left + chgx,
            rcview.bottom - rcview.top + chgy,
            SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
    /* change position and sizes of the controls */
    for( ctrl = GetWindow( hwnd, GW_CHILD); ctrl ; ctrl = GetWindow( ctrl, GW_HWNDNEXT))
    {
1157
        int ctrlid = GetDlgCtrlID( ctrl);
1158 1159 1160 1161 1162 1163 1164
        GetWindowRect( ctrl, &rc);
        MapWindowPoints( NULL, hwnd, (LPPOINT) &rc, 2);
        if( ctrl == fodInfos->DlgInfos.hwndGrip)
        {
            DeferWindowPos( hdwp, ctrl, NULL, rc.left + chgx, rc.top + chgy,
                    0, 0,
                    SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
1165
        }
1166 1167 1168 1169
        else if( rc.top > rcview.bottom)
        {
            /* if it was below the shell view
             * move to bottom */
1170 1171
            switch( ctrlid)
            {
1172
                /* file name (edit or comboboxex) and file types combo change also width */
1173
                case edt1:
1174
                case cmb13:
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
                case cmb1:
                    DeferWindowPos( hdwp, ctrl, NULL, rc.left, rc.top + chgy,
                            rc.right - rc.left + chgx, rc.bottom - rc.top,
                            SWP_NOACTIVATE | SWP_NOZORDER);
                    break;
                    /* then these buttons must move out of the way */
                case IDOK:
                case IDCANCEL:
                case pshHelp:
                    DeferWindowPos( hdwp, ctrl, NULL, rc.left + chgx, rc.top + chgy,
                            0, 0,
                            SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
                    break;
                default:
                DeferWindowPos( hdwp, ctrl, NULL, rc.left, rc.top + chgy,
                        0, 0,
                        SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
            }
1193 1194 1195 1196 1197 1198
        }
        else if( rc.left > rcview.right)
        {
            /* if it was to the right of the shell view
             * move to right */
            DeferWindowPos( hdwp, ctrl, NULL, rc.left + chgx, rc.top,
1199
                    0, 0,
1200 1201
                    SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
        }
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        else
            /* special cases */
        {
            switch( ctrlid)
            {
#if 0 /* this is Win2k, Win XP. Vista and Higher don't move/size these controls */
                case IDC_LOOKIN:
                    DeferWindowPos( hdwp, ctrl, NULL, 0, 0,
                            rc.right - rc.left + chgx, rc.bottom - rc.top,
                            SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
                    break;
                case IDC_TOOLBARSTATIC:
                case IDC_TOOLBAR:
                    DeferWindowPos( hdwp, ctrl, NULL, rc.left + chgx, rc.top,
                            0, 0,
                            SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
                    break;
#endif
                /* not resized in windows. Since wine uses this invisible control
                 * to size the browser view it needs to be resized */
                case IDC_SHELLSTATIC:
                    DeferWindowPos( hdwp, ctrl, NULL, 0, 0,
                            rc.right - rc.left + chgx,
                            rc.bottom - rc.top + chgy,
                            SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
                    break;
1228 1229 1230 1231
                case IDC_TOOLBARPLACES:
                    DeferWindowPos( hdwp, ctrl, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top + chgy,
                                    SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
                    break;
1232 1233
            }
        }
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    }
    if(fodInfos->DlgInfos.hwndCustomDlg &&
        (fodInfos->ofnInfos->Flags & (OFN_ENABLETEMPLATE | OFN_ENABLETEMPLATEHANDLE)))
    {
        for( ctrl = GetWindow( fodInfos->DlgInfos.hwndCustomDlg, GW_CHILD);
                ctrl ; ctrl = GetWindow( ctrl, GW_HWNDNEXT))
        {
            GetWindowRect( ctrl, &rc);
            MapWindowPoints( NULL, hwnd, (LPPOINT) &rc, 2);
            if( rc.top > rcview.bottom)
            {
                /* if it was below the shell view
                 * move to bottom */
                DeferWindowPos( hdwp, ctrl, NULL, rc.left, rc.top + chgy,
                        rc.right - rc.left, rc.bottom - rc.top,
                        SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
            }
            else if( rc.left > rcview.right)
            {
                /* if it was to the right of the shell view
                 * move to right */
                DeferWindowPos( hdwp, ctrl, NULL, rc.left + chgx, rc.top,
                        rc.right - rc.left, rc.bottom - rc.top,
                        SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
            }
        }
1260 1261 1262 1263 1264
        /* size the custom dialog at the end: some applications do some
         * control re-arranging at this point */
        GetClientRect(hwnd, &rc);
        DeferWindowPos( hdwp,fodInfos->DlgInfos.hwndCustomDlg, NULL,
            0, 0, rc.right, rc.bottom, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
1265 1266 1267 1268 1269 1270 1271
    }
    EndDeferWindowPos( hdwp);
    /* should not be needed */
    RedrawWindow( hwnd, NULL, 0, RDW_ALLCHILDREN | RDW_INVALIDATE );
    return TRUE;
}

1272 1273 1274 1275 1276 1277 1278 1279
/***********************************************************************
 *          FileOpenDlgProc95
 *
 * File open dialog procedure
 */
INT_PTR CALLBACK FileOpenDlgProc95(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
#if 0
1280
  TRACE("%p 0x%04x\n", hwnd, uMsg);
1281 1282 1283 1284 1285 1286 1287
#endif

  switch(uMsg)
  {
    case WM_INITDIALOG:
      {
         FileOpenDlgInfos * fodInfos = (FileOpenDlgInfos *)lParam;
1288
         RECT rc, rcstc;
1289 1290
         int gripx = GetSystemMetrics( SM_CYHSCROLL);
         int gripy = GetSystemMetrics( SM_CYVSCROLL);
1291

1292 1293 1294 1295
         /* Some shell namespace extensions depend on COM being initialized. */
         if (SUCCEEDED(OleInitialize(NULL)))
             fodInfos->ole_initialized = TRUE;

1296
         SetPropW(hwnd, L"FileOpenDlgInfos", fodInfos);
1297

1298 1299
         FILEDLG95_InitControls(hwnd);

1300 1301
         if (fodInfos->ofnInfos->Flags & OFN_ENABLESIZING)
         {
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
             DWORD style = GetWindowLongW(hwnd, GWL_STYLE);
             DWORD ex_style = GetWindowLongW(hwnd, GWL_EXSTYLE);
             RECT client, client_adjusted;

             if (fodInfos->ofnInfos->Flags & OFN_ENABLESIZING)
             {
                 style |= WS_SIZEBOX;
                 ex_style |= WS_EX_WINDOWEDGE;
             }
             else
                 style &= ~WS_SIZEBOX;
             SetWindowLongW(hwnd, GWL_STYLE, style);
             SetWindowLongW(hwnd, GWL_EXSTYLE, ex_style);

             GetClientRect( hwnd, &client );
             GetClientRect( hwnd, &client_adjusted );
             AdjustWindowRectEx( &client_adjusted, style, FALSE, ex_style );

             GetWindowRect( hwnd, &rc );
             rc.right += client_adjusted.right - client.right;
             rc.bottom += client_adjusted.bottom - client.bottom;
             SetWindowPos(hwnd, 0, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_FRAMECHANGED | SWP_NOACTIVATE |
                 SWP_NOZORDER | SWP_NOMOVE);

             GetWindowRect( hwnd, &rc );
1327 1328 1329 1330 1331 1332 1333 1334
             fodInfos->DlgInfos.hwndGrip =
                 CreateWindowExA( 0, "SCROLLBAR", NULL,
                     WS_CHILD | WS_GROUP | WS_VISIBLE | WS_CLIPSIBLINGS |
                     SBS_SIZEGRIP | SBS_SIZEBOXBOTTOMRIGHTALIGN,
                     rc.right - gripx, rc.bottom - gripy,
                     gripx, gripy, hwnd, (HMENU) -1, COMDLG32_hInstance, NULL);
         }

1335 1336 1337
      	 fodInfos->DlgInfos.hwndCustomDlg =
     	   CreateTemplateDialog((FileOpenDlgInfos *)lParam, hwnd);

1338
         FILEDLG95_ResizeControls(hwnd, wParam, lParam);
1339 1340
      	 FILEDLG95_FillControls(hwnd, wParam, lParam);

1341 1342 1343
         if( fodInfos->DlgInfos.hwndCustomDlg)
             ShowWindow( fodInfos->DlgInfos.hwndCustomDlg, SW_SHOW);

1344
         if(fodInfos->ofnInfos->Flags & OFN_EXPLORER) {
1345
             SendCustomDlgNotificationMessage(hwnd,CDN_INITDONE);
1346 1347
             SendCustomDlgNotificationMessage(hwnd,CDN_FOLDERCHANGE);
         }
1348

1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
         /* if the app has changed the position of the invisible listbox,
          * change that of the listview (browser) as well */
         GetWindowRect( fodInfos->ShellInfos.hwndView, &rc);
         GetWindowRect( GetDlgItem( hwnd, IDC_SHELLSTATIC ), &rcstc);
         if( !EqualRect( &rc, &rcstc))
         {
             MapWindowPoints( NULL, hwnd, (LPPOINT) &rcstc, 2);
             SetWindowPos( fodInfos->ShellInfos.hwndView, NULL,
                     rcstc.left, rcstc.top, rcstc.right - rcstc.left, rcstc.bottom - rcstc.top,
                     SWP_NOACTIVATE | SWP_NOZORDER);
         }

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
         if (fodInfos->ofnInfos->Flags & OFN_ENABLESIZING)
         {
             GetWindowRect( hwnd, &rc);
             fodInfos->sizedlg.cx = rc.right - rc.left;
             fodInfos->sizedlg.cy = rc.bottom - rc.top;
             fodInfos->initial_size.x = fodInfos->sizedlg.cx;
             fodInfos->initial_size.y = fodInfos->sizedlg.cy;
             GetClientRect( hwnd, &rc);
             SetWindowPos( fodInfos->DlgInfos.hwndGrip, NULL,
                     rc.right - gripx, rc.bottom - gripy,
                     0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER);
1372 1373 1374 1375 1376
             /* resize the dialog to the previous invocation */
             if( MemDialogSize.cx && MemDialogSize.cy)
                 SetWindowPos( hwnd, NULL,
                         0, 0, MemDialogSize.cx, MemDialogSize.cy,
                         SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
1377 1378
         }

1379 1380
         if(fodInfos->ofnInfos->Flags & OFN_EXPLORER)
             SendCustomDlgNotificationMessage(hwnd,CDN_SELCHANGE);
1381

1382 1383
         return 0;
       }
1384
    case WM_SIZE:
1385
      return FILEDLG95_OnWMSize(hwnd, wParam);
1386 1387
    case WM_GETMINMAXINFO:
      return FILEDLG95_OnWMGetMMI( hwnd, (LPMINMAXINFO)lParam);
1388
    case WM_COMMAND:
1389
      return FILEDLG95_OnWMCommand(hwnd, wParam);
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    case WM_DRAWITEM:
      {
        switch(((LPDRAWITEMSTRUCT)lParam)->CtlID)
        {
        case IDC_LOOKIN:
          FILEDLG95_LOOKIN_DrawItem((LPDRAWITEMSTRUCT) lParam);
          return TRUE;
        }
      }
      return FALSE;

    case WM_GETISHELLBROWSER:
      return FILEDLG95_OnWMGetIShellBrowser(hwnd);

    case WM_DESTROY:
1405
      {
1406
          FileOpenDlgInfos * fodInfos = get_filedlg_infoptr(hwnd);
1407 1408 1409
          HWND places_bar = GetDlgItem(hwnd, IDC_TOOLBARPLACES);
          HIMAGELIST himl;

1410 1411
          if (fodInfos && fodInfos->ofnInfos->Flags & OFN_ENABLESIZING)
              MemDialogSize = fodInfos->sizedlg;
1412 1413 1414 1415 1416 1417 1418

          if (places_bar)
          {
              himl = (HIMAGELIST)SendDlgItemMessageW(hwnd, IDC_TOOLBARPLACES, TB_GETIMAGELIST, 0, 0);
              SendDlgItemMessageW(hwnd, IDC_TOOLBARPLACES, TB_SETIMAGELIST, 0, 0);
              ImageList_Destroy(himl);
          }
1419 1420
          return FALSE;
      }
1421 1422

    case WM_NCDESTROY:
1423
        RemovePropW(hwnd, L"FileOpenDlgInfos");
1424 1425
        return 0;

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    case WM_NOTIFY:
    {
	LPNMHDR lpnmh = (LPNMHDR)lParam;
	UINT stringId = -1;

	/* set up the button tooltips strings */
	if(TTN_GETDISPINFOA == lpnmh->code )
	{
	    LPNMTTDISPINFOA lpdi = (LPNMTTDISPINFOA)lParam;
	    switch(lpnmh->idFrom )
	    {
		/* Up folder button */
		case FCIDM_TB_UPFOLDER:
		    stringId = IDS_UPFOLDER;
		    break;
		/* New folder button */
		case FCIDM_TB_NEWFOLDER:
		    stringId = IDS_NEWFOLDER;
		    break;
		/* List option button */
		case FCIDM_TB_SMALLICON:
		    stringId = IDS_LISTVIEW;
		    break;
		/* Details option button */
		case FCIDM_TB_REPORTVIEW:
		    stringId = IDS_REPORTVIEW;
		    break;
		/* Desktop button */
		case FCIDM_TB_DESKTOP:
		    stringId = IDS_TODESKTOP;
		    break;
		default:
		    stringId = 0;
	    }
	    lpdi->hinst = COMDLG32_hInstance;
Kevin Koltzau's avatar
Kevin Koltzau committed
1461
	    lpdi->lpszText =  MAKEINTRESOURCEA(stringId);
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
	}
        return FALSE;
    }
    default :
      if(uMsg >= CDM_FIRST && uMsg <= CDM_LAST)
        return FILEDLG95_HandleCustomDialogMessages(hwnd, uMsg, wParam, lParam);
      return FALSE;
  }
}

1472 1473 1474 1475 1476 1477
static inline BOOL filename_is_edit( const FileOpenDlgInfos *info )
{
    return (info->ofnInfos->lStructSize == OPENFILENAME_SIZE_VERSION_400W) &&
        (info->ofnInfos->Flags & (OFN_ENABLEHOOK | OFN_ENABLETEMPLATE | OFN_ENABLETEMPLATEHANDLE));
}

1478 1479 1480 1481 1482 1483 1484
/***********************************************************************
 *      FILEDLG95_InitControls
 *
 * WM_INITDIALOG message handler (before hook notification)
 */
static LRESULT FILEDLG95_InitControls(HWND hwnd)
{
1485 1486 1487
  BOOL win2000plus = FALSE;
  BOOL win98plus   = FALSE;
  BOOL handledPath = FALSE;
1488
  OSVERSIONINFOW osVi;
1489

1490
  static const TBBUTTON tbb[] =
1491
  {
1492 1493 1494 1495 1496 1497 1498 1499 1500
   {0,                 0,                   TBSTATE_ENABLED, BTNS_SEP, {0, 0}, 0, 0 },
   {VIEW_PARENTFOLDER, FCIDM_TB_UPFOLDER,   TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0 },
   {0,                 0,                   TBSTATE_ENABLED, BTNS_SEP, {0, 0}, 0, 0 },
   {VIEW_NEWFOLDER+1,  FCIDM_TB_DESKTOP,    TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0 },
   {0,                 0,                   TBSTATE_ENABLED, BTNS_SEP, {0, 0}, 0, 0 },
   {VIEW_NEWFOLDER,    FCIDM_TB_NEWFOLDER,  TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0 },
   {0,                 0,                   TBSTATE_ENABLED, BTNS_SEP, {0, 0}, 0, 0 },
   {VIEW_LIST,         FCIDM_TB_SMALLICON,  TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0 },
   {VIEW_DETAILS,      FCIDM_TB_REPORTVIEW, TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0 },
1501
  };
1502 1503
  static const TBADDBITMAP tba = {HINST_COMMCTRL, IDB_VIEW_SMALL_COLOR};

1504 1505 1506
  RECT rectTB;
  RECT rectlook;

1507 1508
  HIMAGELIST toolbarImageList;
  ITEMIDLIST *desktopPidl;
1509
  SHFILEINFOW fileinfo;
1510

1511
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
1512 1513 1514 1515

  TRACE("%p\n", fodInfos);

  /* Get windows version emulating */
1516 1517
  osVi.dwOSVersionInfoSize = sizeof(osVi);
  GetVersionExW(&osVi);
1518 1519 1520 1521 1522 1523 1524 1525
  if (osVi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
    win98plus   = ((osVi.dwMajorVersion > 4) || ((osVi.dwMajorVersion == 4) && (osVi.dwMinorVersion > 0)));
  } else if (osVi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
    win2000plus = (osVi.dwMajorVersion > 4);
    if (win2000plus) win98plus = TRUE;
  }
  TRACE("Running on 2000+ %d, 98+ %d\n", win2000plus, win98plus);

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538

  /* Use either the edit or the comboboxex for the filename control */
  if (filename_is_edit( fodInfos ))
  {
      DestroyWindow( GetDlgItem( hwnd, cmb13 ) );
      fodInfos->DlgInfos.hwndFileName = GetDlgItem( hwnd, edt1 );
  }
  else
  {
      DestroyWindow( GetDlgItem( hwnd, edt1 ) );
      fodInfos->DlgInfos.hwndFileName = GetDlgItem( hwnd, cmb13 );
  }

1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
  /* Get the hwnd of the controls */
  fodInfos->DlgInfos.hwndFileTypeCB = GetDlgItem(hwnd,IDC_FILETYPE);
  fodInfos->DlgInfos.hwndLookInCB = GetDlgItem(hwnd,IDC_LOOKIN);

  GetWindowRect( fodInfos->DlgInfos.hwndLookInCB,&rectlook);
  MapWindowPoints( 0, hwnd,(LPPOINT)&rectlook,2);

  /* construct the toolbar */
  GetWindowRect(GetDlgItem(hwnd,IDC_TOOLBARSTATIC),&rectTB);
  MapWindowPoints( 0, hwnd,(LPPOINT)&rectTB,2);

  rectTB.right = rectlook.right + rectTB.right - rectTB.left;
  rectTB.bottom = rectlook.top - 1 + rectTB.bottom - rectTB.top;
  rectTB.left = rectlook.right;
  rectTB.top = rectlook.top-1;

1555 1556
  if (fodInfos->unicode)
      fodInfos->DlgInfos.hwndTB = CreateWindowExW(0, TOOLBARCLASSNAMEW, NULL,
1557
          WS_CHILD | WS_GROUP | WS_VISIBLE | WS_CLIPSIBLINGS | TBSTYLE_TOOLTIPS | TBSTYLE_FLAT | CCS_NODIVIDER | CCS_NORESIZE,
1558 1559 1560 1561 1562
          rectTB.left, rectTB.top,
          rectTB.right - rectTB.left, rectTB.bottom - rectTB.top,
          hwnd, (HMENU)IDC_TOOLBAR, COMDLG32_hInstance, NULL);
  else
      fodInfos->DlgInfos.hwndTB = CreateWindowExA(0, TOOLBARCLASSNAMEA, NULL,
1563
          WS_CHILD | WS_GROUP | WS_VISIBLE | WS_CLIPSIBLINGS | TBSTYLE_TOOLTIPS | TBSTYLE_FLAT | CCS_NODIVIDER | CCS_NORESIZE,
1564 1565 1566
          rectTB.left, rectTB.top,
          rectTB.right - rectTB.left, rectTB.bottom - rectTB.top,
          hwnd, (HMENU)IDC_TOOLBAR, COMDLG32_hInstance, NULL);
1567

1568
  SendMessageW(fodInfos->DlgInfos.hwndTB, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0);
1569 1570

/* FIXME: use TB_LOADIMAGES when implemented */
1571
/*  SendMessageW(fodInfos->DlgInfos.hwndTB, TB_LOADIMAGES, IDB_VIEW_SMALL_COLOR, HINST_COMMCTRL);*/
1572
  SendMessageW(fodInfos->DlgInfos.hwndTB, TB_SETMAXTEXTROWS, 0, 0);
1573 1574 1575 1576 1577
  SendMessageW(fodInfos->DlgInfos.hwndTB, TB_ADDBITMAP, 12, (LPARAM) &tba);

  /* Retrieve and add desktop icon to the toolbar */
  toolbarImageList = (HIMAGELIST)SendMessageW(fodInfos->DlgInfos.hwndTB, TB_GETIMAGELIST, 0, 0L);
  SHGetSpecialFolderLocation(hwnd, CSIDL_DESKTOP, &desktopPidl);
1578
  SHGetFileInfoW((const WCHAR *)desktopPidl, 0, &fileinfo, sizeof(fileinfo),
1579
    SHGFI_PIDL | SHGFI_ICON | SHGFI_SMALLICON);
1580
  ImageList_AddIcon(toolbarImageList, fileinfo.hIcon);
1581

1582
  DestroyIcon(fileinfo.hIcon);
1583
  CoTaskMemFree(desktopPidl);
1584

1585
  /* Finish Toolbar Construction */
1586
  SendMessageW(fodInfos->DlgInfos.hwndTB, TB_ADDBUTTONSW, 9, (LPARAM) tbb);
1587
  SendMessageW(fodInfos->DlgInfos.hwndTB, TB_AUTOSIZE, 0, 0);
1588

1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
  if (is_places_bar_enabled(fodInfos))
  {
      TBBUTTON tb = { 0 };
      HIMAGELIST himl;
      RECT rect;
      int i, cx;

      SendDlgItemMessageW(hwnd, IDC_TOOLBARPLACES, TB_BUTTONSTRUCTSIZE, 0, 0);
      GetClientRect(GetDlgItem(hwnd, IDC_TOOLBARPLACES), &rect);
      cx = rect.right - rect.left;

      SendDlgItemMessageW(hwnd, IDC_TOOLBARPLACES, TB_SETBUTTONWIDTH, 0, MAKELPARAM(cx, cx));
      himl = ImageList_Create(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), ILC_COLOR32, 4, 1);
1602 1603 1604

      filedlg_collect_places_pidls(fodInfos);
      for (i = 0; i < ARRAY_SIZE(fodInfos->places); i++)
1605
      {
1606 1607 1608 1609
          int index;

          if (!fodInfos->places[i])
              continue;
1610 1611

          memset(&fileinfo, 0, sizeof(fileinfo));
1612
          SHGetFileInfoW((const WCHAR *)fodInfos->places[i], 0, &fileinfo, sizeof(fileinfo),
1613
              SHGFI_PIDL | SHGFI_DISPLAYNAME | SHGFI_ICON);
1614
          index = ImageList_AddIcon(himl, fileinfo.hIcon);
1615

1616
          tb.iBitmap = index;
1617 1618
          tb.iString = (INT_PTR)fileinfo.szDisplayName;
          tb.fsState = TBSTATE_ENABLED | TBSTATE_WRAP;
1619
          tb.idCommand = TBPLACES_CMDID_PLACE0 + i;
1620 1621 1622 1623 1624 1625 1626 1627 1628
          SendDlgItemMessageW(hwnd, IDC_TOOLBARPLACES, TB_ADDBUTTONSW, 1, (LPARAM)&tb);

          DestroyIcon(fileinfo.hIcon);
      }

      SendDlgItemMessageW(hwnd, IDC_TOOLBARPLACES, TB_SETIMAGELIST, 0, (LPARAM)himl);
      SendDlgItemMessageW(hwnd, IDC_TOOLBARPLACES, TB_SETBUTTONSIZE, 0, MAKELPARAM(cx, cx * 3 / 4));
  }

1629 1630 1631 1632 1633 1634 1635
  /* Set the window text with the text specified in the OPENFILENAME structure */
  if(fodInfos->title)
  {
      SetWindowTextW(hwnd,fodInfos->title);
  }
  else if (fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG)
  {
1636
      WCHAR buf[64];
1637
      LoadStringW(COMDLG32_hInstance, IDS_SAVE_AS, buf, ARRAY_SIZE(buf));
1638
      SetWindowTextW(hwnd, buf);
1639 1640 1641 1642
  }

  /* Initialise the file name edit control */
  handledPath = FALSE;
1643
  TRACE("Before manipulation, file = %s, dir = %s\n", debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));
1644 1645 1646 1647 1648

  if(fodInfos->filename)
  {
      /* 1. If win2000 or higher and filename contains a path, use it
         in preference over the lpstrInitialDir                       */
1649
      if (win2000plus && *fodInfos->filename && wcspbrk(fodInfos->filename, L"\\")) {
1650 1651 1652 1653 1654 1655 1656
         WCHAR tmpBuf[MAX_PATH];
         WCHAR *nameBit;
         DWORD result;

         result = GetFullPathNameW(fodInfos->filename, MAX_PATH, tmpBuf, &nameBit);
         if (result) {

1657 1658 1659 1660 1661 1662 1663 1664 1665
            /* nameBit is always shorter than the original filename. It may be NULL
             * when the filename contains only a drive name instead of file name */
            if (nameBit)
            {
                lstrcpyW(fodInfos->filename,nameBit);
                *nameBit = 0x00;
            }
            else
                *fodInfos->filename = '\0';
1666

1667 1668
            heap_free(fodInfos->initdir);
            fodInfos->initdir = heap_alloc((lstrlenW(tmpBuf) + 1)*sizeof(WCHAR));
1669
            lstrcpyW(fodInfos->initdir, tmpBuf);
1670 1671 1672 1673
            handledPath = TRUE;
            TRACE("Value in Filename includes path, overriding InitialDir: %s, %s\n",
                    debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));
         }
1674
         SetWindowTextW( fodInfos->DlgInfos.hwndFileName, fodInfos->filename );
1675 1676

      } else {
1677
         SetWindowTextW( fodInfos->DlgInfos.hwndFileName, fodInfos->filename );
1678 1679 1680 1681
      }
  }

  /* 2. (All platforms) If initdir is not null, then use it */
1682
  if (!handledPath && fodInfos->initdir && *fodInfos->initdir)
1683
  {
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
        /* Work out the proper path as supplied one might be relative          */
        /* (Here because supplying '.' as dir browses to My Computer)          */
        WCHAR tmpBuf[MAX_PATH];
        WCHAR tmpBuf2[MAX_PATH];
        WCHAR *nameBit;
        DWORD result;

        lstrcpyW(tmpBuf, fodInfos->initdir);
        if (PathFileExistsW(tmpBuf)) {
            /* initdir does not have to be a directory. If a file is
             * specified, the dir part is taken */
            if (PathIsDirectoryW(tmpBuf)) {
                PathAddBackslashW(tmpBuf);
1697
                lstrcatW(tmpBuf, L"*");
1698 1699 1700 1701
            }
            result = GetFullPathNameW(tmpBuf, MAX_PATH, tmpBuf2, &nameBit);
            if (result) {
                *nameBit = 0x00;
1702 1703
                heap_free(fodInfos->initdir);
                fodInfos->initdir = heap_alloc((lstrlenW(tmpBuf2) + 1) * sizeof(WCHAR));
1704 1705 1706 1707 1708 1709 1710
                lstrcpyW(fodInfos->initdir, tmpBuf2);
                handledPath = TRUE;
                TRACE("Value in InitDir changed to %s\n", debugstr_w(fodInfos->initdir));
            }
        }
        else if (fodInfos->initdir)
        {
1711
            heap_free(fodInfos->initdir);
1712 1713 1714
            fodInfos->initdir = NULL;
            TRACE("Value in InitDir is not an existing path, changed to (nil)\n");
        }
1715 1716
  }

1717
  if (!handledPath && (!fodInfos->initdir || !*fodInfos->initdir))
1718 1719
  {
      /* 3. All except w2k+: if filename contains a path use it */
1720 1721
      if (!win2000plus && fodInfos->filename && *fodInfos->filename &&
          wcspbrk(fodInfos->filename, L"\\")) {
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
         WCHAR tmpBuf[MAX_PATH];
         WCHAR *nameBit;
         DWORD result;

         result = GetFullPathNameW(fodInfos->filename, MAX_PATH,
                                  tmpBuf, &nameBit);
         if (result) {
            int len;

            /* nameBit is always shorter than the original filename */
1732
            lstrcpyW(fodInfos->filename, nameBit);
1733 1734
            *nameBit = 0x00;

1735
            len = lstrlenW(tmpBuf);
1736 1737
            heap_free(fodInfos->initdir);
            fodInfos->initdir = heap_alloc((len+1)*sizeof(WCHAR));
1738
            lstrcpyW(fodInfos->initdir, tmpBuf);
1739 1740 1741 1742 1743

            handledPath = TRUE;
            TRACE("Value in Filename includes path, overriding initdir: %s, %s\n",
                 debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));
         }
1744
         SetWindowTextW( fodInfos->DlgInfos.hwndFileName, fodInfos->filename );
1745 1746
      }

1747
      /* 4. Win2000+: Recently used */
1748
      if (!handledPath && win2000plus) {
1749
          fodInfos->initdir = heap_alloc(MAX_PATH * sizeof(WCHAR));
1750 1751 1752 1753 1754 1755 1756
          fodInfos->initdir[0] = '\0';

          FILEDLG95_MRU_load_filename(fodInfos->initdir);

          if (fodInfos->initdir[0] && PathFileExistsW(fodInfos->initdir)){
             handledPath = TRUE;
          }else{
1757
             heap_free(fodInfos->initdir);
1758 1759 1760 1761 1762
             fodInfos->initdir = NULL;
          }
      }

      /* 5. win98+ and win2000+ if any files of specified filter types in
1763
            current directory, use it                                      */
1764
      if (win98plus && !handledPath && fodInfos->filter && *fodInfos->filter) {
1765 1766 1767 1768 1769

         LPCWSTR lpstrPos = fodInfos->filter;
         WIN32_FIND_DATAW FindFileData;
         HANDLE hFind;

1770
         while (1)
1771 1772 1773 1774 1775
         {
           /* filter is a list...  title\0ext\0......\0\0 */

           /* Skip the title */
           if(! *lpstrPos) break;	/* end */
1776
           lpstrPos += lstrlenW(lpstrPos) + 1;
1777 1778 1779 1780 1781 1782 1783 1784

           /* See if any files exist in the current dir with this extension */
           if(! *lpstrPos) break;	/* end */

           hFind = FindFirstFileW(lpstrPos, &FindFileData);

           if (hFind == INVALID_HANDLE_VALUE) {
               /* None found - continue search */
1785
               lpstrPos += lstrlenW(lpstrPos) + 1;
1786 1787 1788

           } else {

1789 1790
               heap_free(fodInfos->initdir);
               fodInfos->initdir = heap_alloc(MAX_PATH * sizeof(WCHAR));
1791 1792 1793 1794 1795
               GetCurrentDirectoryW(MAX_PATH, fodInfos->initdir);

               handledPath = TRUE;
               TRACE("No initial dir specified, but files of type %s found in current, so using it\n",
                 debugstr_w(lpstrPos));
1796
               FindClose(hFind);
1797 1798 1799 1800 1801 1802
               break;
           }
         }
      }

      /* 6. Win98+ and 2000+: Use personal files dir, others use current dir */
1803
      if (!handledPath && (win2000plus || win98plus)) {
1804
          fodInfos->initdir = heap_alloc(MAX_PATH * sizeof(WCHAR));
1805

1806
          if (SHGetFolderPathW(hwnd, CSIDL_PERSONAL, 0, 0, fodInfos->initdir) == S_OK)
1807
          {
1808 1809 1810 1811 1812 1813 1814
              if (SHGetFolderPathW(hwnd, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, 0, 0, fodInfos->initdir) == S_OK)
              {
                  /* last fallback */
                  GetCurrentDirectoryW(MAX_PATH, fodInfos->initdir);
                  TRACE("No personal or desktop dir, using cwd as failsafe: %s\n", debugstr_w(fodInfos->initdir));
              }
              else
1815 1816
                TRACE("No personal dir, using desktop instead: %s\n", debugstr_w(fodInfos->initdir));
          }
1817 1818 1819
          else
              TRACE("No initial dir specified, using personal files dir of %s\n", debugstr_w(fodInfos->initdir));

1820
          handledPath = TRUE;
1821
      } else if (!handledPath) {
1822
          fodInfos->initdir = heap_alloc(MAX_PATH * sizeof(WCHAR));
1823 1824 1825 1826 1827
          GetCurrentDirectoryW(MAX_PATH, fodInfos->initdir);
          handledPath = TRUE;
          TRACE("No initial dir specified, using current dir of %s\n", debugstr_w(fodInfos->initdir));
      }
  }
1828
  SetFocus( fodInfos->DlgInfos.hwndFileName );
1829 1830 1831 1832 1833
  TRACE("After manipulation, file = %s, dir = %s\n", debugstr_w(fodInfos->filename), debugstr_w(fodInfos->initdir));

  /* Must the open as read only check box be checked ?*/
  if(fodInfos->ofnInfos->Flags & OFN_READONLY)
  {
1834
    SendDlgItemMessageW(hwnd,IDC_OPENREADONLY,BM_SETCHECK,TRUE,0);
1835 1836 1837
  }

  /* Must the open as read only check box be hidden? */
1838
  if (filedialog_is_readonly_hidden(fodInfos))
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
  {
    ShowWindow(GetDlgItem(hwnd,IDC_OPENREADONLY),SW_HIDE);
    EnableWindow(GetDlgItem(hwnd, IDC_OPENREADONLY), FALSE);
  }

  /* Must the help button be hidden? */
  if (!(fodInfos->ofnInfos->Flags & OFN_SHOWHELP))
  {
    ShowWindow(GetDlgItem(hwnd, pshHelp), SW_HIDE);
    EnableWindow(GetDlgItem(hwnd, pshHelp), FALSE);
  }

1851
  /* change Open to Save */
1852 1853
  if (fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG)
  {
1854
      WCHAR buf[16];
1855
      LoadStringW(COMDLG32_hInstance, IDS_SAVE_BUTTON, buf, ARRAY_SIZE(buf));
1856
      SetDlgItemTextW(hwnd, IDOK, buf);
1857
      LoadStringW(COMDLG32_hInstance, IDS_SAVE_IN, buf, ARRAY_SIZE(buf));
1858
      SetDlgItemTextW(hwnd, IDC_LOOKINSTATIC, buf);
1859
  }
1860 1861 1862 1863

  /* Initialize the filter combo box */
  FILEDLG95_FILETYPE_Init(hwnd);

1864 1865 1866
  return 0;
}

1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
/***********************************************************************
 *      FILEDLG95_ResizeControls
 *
 * WM_INITDIALOG message handler (after hook notification)
 */
static LRESULT FILEDLG95_ResizeControls(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
  FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) lParam;

  if (fodInfos->DlgInfos.hwndCustomDlg)
  {
    RECT rc;
    UINT flags = SWP_NOACTIVATE;

    ArrangeCtrlPositions(fodInfos->DlgInfos.hwndCustomDlg, hwnd,
1882
        filedialog_is_readonly_hidden(fodInfos) && !(fodInfos->ofnInfos->Flags & OFN_SHOWHELP));
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894

    /* resize the custom dialog to the parent size */
    if (fodInfos->ofnInfos->Flags & (OFN_ENABLETEMPLATE | OFN_ENABLETEMPLATEHANDLE))
      GetClientRect(hwnd, &rc);
    else
    {
      /* our own fake template is zero sized and doesn't have children, so
       * there is no need to resize it. Picasa depends on it.
       */
      flags |= SWP_NOSIZE;
      SetRectEmpty(&rc);
    }
1895 1896
    SetWindowPos(fodInfos->DlgInfos.hwndCustomDlg, HWND_BOTTOM,
                 0, 0, rc.right, rc.bottom, flags);
1897 1898 1899
  }
  else
  {
1900
    /* Resize the height; if opened as read-only, checkbox and help button are
1901 1902
     * hidden and we are not using a custom template nor a customDialog
     */
1903
    if (filedialog_is_readonly_hidden(fodInfos) &&
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
                (!(fodInfos->ofnInfos->Flags &
                   (OFN_SHOWHELP|OFN_ENABLETEMPLATE|OFN_ENABLETEMPLATEHANDLE))))
    {
      RECT rectDlg, rectHelp, rectCancel;
      GetWindowRect(hwnd, &rectDlg);
      GetWindowRect(GetDlgItem(hwnd, pshHelp), &rectHelp);
      GetWindowRect(GetDlgItem(hwnd, IDCANCEL), &rectCancel);
      /* subtract the height of the help button plus the space between the help
       * button and the cancel button to the height of the dialog
       */
      SetWindowPos(hwnd, 0, 0, 0, rectDlg.right-rectDlg.left,
          (rectDlg.bottom-rectDlg.top) - (rectHelp.bottom - rectCancel.bottom),
          SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);
    }
  }
  return TRUE;
}

1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
/***********************************************************************
 *      FILEDLG95_FillControls
 *
 * WM_INITDIALOG message handler (after hook notification)
 */
static LRESULT FILEDLG95_FillControls(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
  LPITEMIDLIST pidlItemId = NULL;

  FileOpenDlgInfos *fodInfos = (FileOpenDlgInfos *) lParam;

  TRACE("dir=%s file=%s\n",
  debugstr_w(fodInfos->initdir), debugstr_w(fodInfos->filename));

  /* Get the initial directory pidl */

  if(!(pidlItemId = GetPidlFromName(fodInfos->Shell.FOIShellFolder,fodInfos->initdir)))
  {
    WCHAR path[MAX_PATH];

    GetCurrentDirectoryW(MAX_PATH,path);
    pidlItemId = GetPidlFromName(fodInfos->Shell.FOIShellFolder, path);
  }

  /* Initialise shell objects */
  FILEDLG95_SHELL_Init(hwnd);

  /* Initialize the Look In combo box */
  FILEDLG95_LOOKIN_Init(fodInfos->DlgInfos.hwndLookInCB);

  /* Browse to the initial directory */
  IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser,pidlItemId, SBSP_ABSOLUTE);

1955
  ILFree(pidlItemId);
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969

  return TRUE;
}
/***********************************************************************
 *      FILEDLG95_Clean
 *
 * Regroups all the cleaning functions of the filedlg
 */
void FILEDLG95_Clean(HWND hwnd)
{
      FILEDLG95_FILETYPE_Clean(hwnd);
      FILEDLG95_LOOKIN_Clean(hwnd);
      FILEDLG95_SHELL_Clean(hwnd);
}
1970 1971 1972


/***********************************************************************
1973
 * Browse to arbitrary pidl
1974
 */
1975
static void filedlg_browse_to_pidl(const FileOpenDlgInfos *info, LPITEMIDLIST pidl)
1976
{
1977
    TRACE("%p, %p\n", info->ShellInfos.hwndOwner, pidl);
1978 1979 1980 1981 1982 1983

    IShellBrowser_BrowseObject(info->Shell.FOIShellBrowser, pidl, SBSP_ABSOLUTE);
    if (info->ofnInfos->Flags & OFN_EXPLORER)
        SendCustomDlgNotificationMessage(info->ShellInfos.hwndOwner, CDN_FOLDERCHANGE);
}

1984 1985 1986 1987 1988
/***********************************************************************
 *      FILEDLG95_OnWMCommand
 *
 * WM_COMMAND message handler
 */
1989
static LRESULT FILEDLG95_OnWMCommand(HWND hwnd, WPARAM wParam)
1990
{
1991
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
1992
  WORD wNotifyCode = HIWORD(wParam); /* notification code */
1993
  WORD id = LOWORD(wParam);         /* item, control, or accelerator identifier */
1994

1995
  switch (id)
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
  {
    /* OK button */
  case IDOK:
    FILEDLG95_OnOpen(hwnd);
    break;
    /* Cancel button */
  case IDCANCEL:
    FILEDLG95_Clean(hwnd);
    EndDialog(hwnd, FALSE);
    break;
    /* Filetype combo box */
  case IDC_FILETYPE:
    FILEDLG95_FILETYPE_OnCommand(hwnd,wNotifyCode);
    break;
    /* LookIn combo box */
  case IDC_LOOKIN:
    FILEDLG95_LOOKIN_OnCommand(hwnd,wNotifyCode);
    break;

  /* --- toolbar --- */
    /* Up folder button */
  case FCIDM_TB_UPFOLDER:
    FILEDLG95_SHELL_UpFolder(hwnd);
    break;
    /* New folder button */
  case FCIDM_TB_NEWFOLDER:
    FILEDLG95_SHELL_ExecuteCommand(hwnd,CMDSTR_NEWFOLDERA);
    break;
    /* List option button */
  case FCIDM_TB_SMALLICON:
    FILEDLG95_SHELL_ExecuteCommand(hwnd,CMDSTR_VIEWLISTA);
    break;
    /* Details option button */
  case FCIDM_TB_REPORTVIEW:
    FILEDLG95_SHELL_ExecuteCommand(hwnd,CMDSTR_VIEWDETAILSA);
    break;
2032

2033
  case FCIDM_TB_DESKTOP:
2034 2035
  {
    LPITEMIDLIST pidl;
2036

2037 2038
    SHGetSpecialFolderLocation(0, CSIDL_DESKTOP, &pidl);
    filedlg_browse_to_pidl(fodInfos, pidl);
2039
    ILFree(pidl);
2040
    break;
2041
  }
2042

2043 2044 2045 2046 2047 2048 2049
  /* Places bar */
  case TBPLACES_CMDID_PLACE0:
  case TBPLACES_CMDID_PLACE1:
  case TBPLACES_CMDID_PLACE2:
  case TBPLACES_CMDID_PLACE3:
  case TBPLACES_CMDID_PLACE4:
    filedlg_browse_to_pidl(fodInfos, fodInfos->places[id - TBPLACES_CMDID_PLACE0]);
2050 2051
    break;

2052 2053
  case edt1:
  case cmb13:
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
    break;

  }
  /* Do not use the listview selection anymore */
  fodInfos->DlgInfos.dwDlgProp &= ~FODPROP_USEVIEW;
  return 0;
}

/***********************************************************************
 *      FILEDLG95_OnWMGetIShellBrowser
 *
 * WM_GETISHELLBROWSER message handler
 */
static LRESULT FILEDLG95_OnWMGetIShellBrowser(HWND hwnd)
{
2069
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
2070 2071 2072

  TRACE("\n");

2073
  SetWindowLongPtrW(hwnd,DWLP_MSGRESULT,(LONG_PTR)fodInfos->Shell.FOIShellBrowser);
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090

  return TRUE;
}


/***********************************************************************
 *      FILEDLG95_SendFileOK
 *
 * Sends the CDN_FILEOK notification if required
 *
 * RETURNS
 *  TRUE if the dialog should close
 *  FALSE if the dialog should not be closed
 */
static BOOL FILEDLG95_SendFileOK( HWND hwnd, FileOpenDlgInfos *fodInfos )
{
    /* ask the hook if we can close */
2091
    if (is_dialog_hooked(fodInfos))
2092
    {
2093
        LRESULT retval = 0;
2094

2095 2096
        TRACE("---\n");
        /* First send CDN_FILEOK as MSDN doc says */
2097 2098
        if(fodInfos->ofnInfos->Flags & OFN_EXPLORER)
            retval = SendCustomDlgNotificationMessage(hwnd,CDN_FILEOK);
2099
        if( retval)
2100 2101
        {
            TRACE("canceled\n");
2102
            return FALSE;
2103
        }
2104 2105

        /* fodInfos->ofnInfos points to an ASCII or UNICODE structure as appropriate */
2106 2107
        retval = SendMessageW(fodInfos->DlgInfos.hwndCustomDlg,
                              fodInfos->HookMsg.fileokstring, 0, (LPARAM)fodInfos->ofnInfos);
2108
        if( retval)
2109 2110
        {
            TRACE("canceled\n");
2111
            return FALSE;
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
        }
    }
    return TRUE;
}

/***********************************************************************
 *      FILEDLG95_OnOpenMultipleFiles
 *
 * Handles the opening of multiple files.
 *
 * FIXME
 *  check destination buffer size
 */
BOOL FILEDLG95_OnOpenMultipleFiles(HWND hwnd, LPWSTR lpstrFileList, UINT nFileCount, UINT sizeUsed)
{
2127
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
2128 2129 2130 2131 2132 2133 2134
  WCHAR   lpstrPathSpec[MAX_PATH] = {0};
  UINT   nCount, nSizePath;

  TRACE("\n");

  if(fodInfos->unicode)
  {
Jacek Caban's avatar
Jacek Caban committed
2135
     LPOPENFILENAMEW ofn = fodInfos->ofnInfos;
2136 2137 2138 2139
     ofn->lpstrFile[0] = '\0';
  }
  else
  {
Jacek Caban's avatar
Jacek Caban committed
2140
     LPOPENFILENAMEA ofn = (LPOPENFILENAMEA) fodInfos->ofnInfos;
2141 2142 2143
     ofn->lpstrFile[0] = '\0';
  }

2144
  COMDLG32_GetDisplayNameOf( fodInfos->ShellInfos.pidlAbsCurrent, lpstrPathSpec );
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165

  if ( !(fodInfos->ofnInfos->Flags & OFN_NOVALIDATE) &&
      ( fodInfos->ofnInfos->Flags & OFN_FILEMUSTEXIST) &&
       ! ( fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG ) )
  {
    LPWSTR lpstrTemp = lpstrFileList;

    for ( nCount = 0; nCount < nFileCount; nCount++ )
    {
      LPITEMIDLIST pidl;

      pidl = GetPidlFromName(fodInfos->Shell.FOIShellFolder, lpstrTemp);
      if (!pidl)
      {
        WCHAR lpstrNotFound[100];
        WCHAR lpstrMsg[100];
        WCHAR tmp[400];

        LoadStringW(COMDLG32_hInstance, IDS_FILENOTFOUND, lpstrNotFound, 100);
        LoadStringW(COMDLG32_hInstance, IDS_VERIFYFILE, lpstrMsg, 100);

2166
        lstrcpyW(tmp, lpstrTemp);
2167
        lstrcatW(tmp, L"\n");
2168
        lstrcatW(tmp, lpstrNotFound);
2169
        lstrcatW(tmp, L"\n");
2170
        lstrcatW(tmp, lpstrMsg);
2171 2172 2173 2174 2175 2176

        MessageBoxW(hwnd, tmp, fodInfos->title, MB_OK | MB_ICONEXCLAMATION);
        return FALSE;
      }

      /* move to the next file in the list of files */
2177
      lpstrTemp += lstrlenW(lpstrTemp) + 1;
2178
      ILFree(pidl);
2179 2180 2181
    }
  }

2182
  nSizePath = lstrlenW(lpstrPathSpec) + 1;
2183 2184 2185
  if ( !(fodInfos->ofnInfos->Flags & OFN_EXPLORER) )
  {
    /* For "oldstyle" dialog the components have to
2186
       be separated by blanks (not '\0'!) and short
2187
       filenames have to be used! */
2188
    FIXME("Components have to be separated by blanks\n");
2189 2190 2191
  }
  if(fodInfos->unicode)
  {
Jacek Caban's avatar
Jacek Caban committed
2192
    LPOPENFILENAMEW ofn = fodInfos->ofnInfos;
2193
    lstrcpyW( ofn->lpstrFile, lpstrPathSpec);
2194 2195 2196 2197
    memcpy( ofn->lpstrFile + nSizePath, lpstrFileList, sizeUsed*sizeof(WCHAR) );
  }
  else
  {
Jacek Caban's avatar
Jacek Caban committed
2198
    LPOPENFILENAMEA ofn = (LPOPENFILENAMEA)fodInfos->ofnInfos;
2199 2200 2201

    if (ofn->lpstrFile != NULL)
    {
2202
      nSizePath = WideCharToMultiByte(CP_ACP, 0, lpstrPathSpec, -1,
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
			  ofn->lpstrFile, ofn->nMaxFile, NULL, NULL);
      if (ofn->nMaxFile > nSizePath)
      {
	WideCharToMultiByte(CP_ACP, 0, lpstrFileList, sizeUsed,
			    ofn->lpstrFile + nSizePath,
			    ofn->nMaxFile - nSizePath, NULL, NULL);
      }
    }
  }

2213
  fodInfos->ofnInfos->nFileOffset = nSizePath;
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
  fodInfos->ofnInfos->nFileExtension = 0;

  if ( !FILEDLG95_SendFileOK(hwnd, fodInfos) )
    return FALSE;

  /* clean and exit */
  FILEDLG95_Clean(hwnd);
  return EndDialog(hwnd,TRUE);
}

2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
/* Returns the 'slot name' of the given module_name in the registry's
 * most-recently-used list.  This will be an ASCII value in the
 * range ['a','z'). Returns zero on error.
 *
 * The slot's value in the registry has the form:
 *   module_name\0mru_path\0
 *
 * If stored_path is given, then stored_path will contain the path name
 * stored in the registry's MRU list for the given module_name.
 *
 * If hkey_ret is given, then hkey_ret will be a handle to the registry's
 * MRU list key for the given module_name.
 */
static WCHAR FILEDLG95_MRU_get_slot(LPCWSTR module_name, LPWSTR stored_path, PHKEY hkey_ret)
{
    WCHAR mru_list[32], *cur_mru_slot;
    BOOL taken[25] = {0};
    DWORD mru_list_size = sizeof(mru_list), key_type = -1, i;
    HKEY hkey_tmp, *hkey;
    LONG ret;

    if(hkey_ret)
        hkey = hkey_ret;
    else
        hkey = &hkey_tmp;

    if(stored_path)
        *stored_path = '\0';

2253 2254
    ret = RegCreateKeyW(HKEY_CURRENT_USER,
            L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedMRU", hkey);
2255 2256 2257 2258 2259
    if(ret){
        WARN("Unable to create MRU key: %d\n", ret);
        return 0;
    }

2260
    ret = RegGetValueW(*hkey, NULL, L"MRUList", RRF_RT_REG_SZ, &key_type,
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
            (LPBYTE)mru_list, &mru_list_size);
    if(ret || key_type != REG_SZ){
        if(ret == ERROR_FILE_NOT_FOUND)
            return 'a';

        WARN("Error getting MRUList data: type: %d, ret: %d\n", key_type, ret);
        RegCloseKey(*hkey);
        return 0;
    }

    for(cur_mru_slot = mru_list; *cur_mru_slot; ++cur_mru_slot){
        WCHAR value_data[MAX_PATH], value_name[2] = {0};
        DWORD value_data_size = sizeof(value_data);

        *value_name = *cur_mru_slot;

        ret = RegGetValueW(*hkey, NULL, value_name, RRF_RT_REG_BINARY,
                &key_type, (LPBYTE)value_data, &value_data_size);
        if(ret || key_type != REG_BINARY){
            WARN("Error getting MRU slot data: type: %d, ret: %d\n", key_type, ret);
            continue;
        }

2284
        if(!wcsicmp(module_name, value_data)){
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
            if(!hkey_ret)
                RegCloseKey(*hkey);
            if(stored_path)
                lstrcpyW(stored_path, value_data + lstrlenW(value_data) + 1);
            return *value_name;
        }
    }

    if(!hkey_ret)
        RegCloseKey(*hkey);

    /* the module name isn't in the registry, so find the next open slot */
    for(cur_mru_slot = mru_list; *cur_mru_slot; ++cur_mru_slot)
        taken[*cur_mru_slot - 'a'] = TRUE;
    for(i = 0; i < 25; ++i){
        if(!taken[i])
            return i + 'a';
    }

    /* all slots are taken, so return the last one in MRUList */
    --cur_mru_slot;
    return *cur_mru_slot;
}

/* save the given filename as most-recently-used path for this module */
static void FILEDLG95_MRU_save_filename(LPCWSTR filename)
{
    WCHAR module_path[MAX_PATH], *module_name, slot, slot_name[2] = {0};
    LONG ret;
    HKEY hkey;

    /* get the current executable's name */
2317 2318
    if (!GetModuleFileNameW(GetModuleHandleW(NULL), module_path, ARRAY_SIZE(module_path)))
    {
2319 2320 2321
        WARN("GotModuleFileName failed: %d\n", GetLastError());
        return;
    }
2322
    module_name = wcsrchr(module_path, '\\');
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
    if(!module_name)
        module_name = module_path;
    else
        module_name += 1;

    slot = FILEDLG95_MRU_get_slot(module_name, NULL, &hkey);
    if(!slot)
        return;
    *slot_name = slot;

    { /* update the slot's info */
        WCHAR *path_ends, *final;
        DWORD path_len, final_len;

        /* use only the path segment of `filename' */
2338
        path_ends = wcsrchr(filename, '\\');
2339 2340 2341 2342
        path_len = path_ends - filename;

        final_len = path_len + lstrlenW(module_name) + 2;

2343
        final = heap_alloc(final_len * sizeof(WCHAR));
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
        if(!final)
            return;
        lstrcpyW(final, module_name);
        memcpy(final + lstrlenW(final) + 1, filename, path_len * sizeof(WCHAR));
        final[final_len-1] = '\0';

        ret = RegSetValueExW(hkey, slot_name, 0, REG_BINARY, (LPBYTE)final,
                final_len * sizeof(WCHAR));
        if(ret){
            WARN("Error saving MRU data to slot %s: %d\n", wine_dbgstr_w(slot_name), ret);
2354
            heap_free(final);
2355 2356 2357 2358
            RegCloseKey(hkey);
            return;
        }

2359
        heap_free(final);
2360 2361 2362 2363 2364 2365 2366
    }

    { /* update MRUList value */
        WCHAR old_mru_list[32], new_mru_list[32];
        WCHAR *old_mru_slot, *new_mru_slot = new_mru_list;
        DWORD mru_list_size = sizeof(old_mru_list), key_type;

2367
        ret = RegGetValueW(hkey, NULL, L"MRUList", RRF_RT_ANY, &key_type,
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
                (LPBYTE)old_mru_list, &mru_list_size);
        if(ret || key_type != REG_SZ){
            if(ret == ERROR_FILE_NOT_FOUND){
                new_mru_list[0] = slot;
                new_mru_list[1] = '\0';
            }else{
                WARN("Error getting MRUList data: type: %d, ret: %d\n", key_type, ret);
                RegCloseKey(hkey);
                return;
            }
        }else{
            /* copy old list data over so that the new slot is at the start
             * of the list */
            *new_mru_slot++ = slot;
            for(old_mru_slot = old_mru_list; *old_mru_slot; ++old_mru_slot){
                if(*old_mru_slot != slot)
                    *new_mru_slot++ = *old_mru_slot;
            }
            *new_mru_slot = '\0';
        }

2389
        ret = RegSetValueExW(hkey, L"MRUList", 0, REG_SZ, (LPBYTE)new_mru_list,
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
                (lstrlenW(new_mru_list) + 1) * sizeof(WCHAR));
        if(ret){
            WARN("Error saving MRUList data: %d\n", ret);
            RegCloseKey(hkey);
            return;
        }
    }
}

/* load the most-recently-used path for this module */
static void FILEDLG95_MRU_load_filename(LPWSTR stored_path)
{
    WCHAR module_path[MAX_PATH], *module_name;

    /* get the current executable's name */
2405 2406
    if (!GetModuleFileNameW(GetModuleHandleW(NULL), module_path, ARRAY_SIZE(module_path)))
    {
2407 2408 2409
        WARN("GotModuleFileName failed: %d\n", GetLastError());
        return;
    }
2410
    module_name = wcsrchr(module_path, '\\');
2411 2412 2413 2414 2415 2416 2417 2418 2419
    if(!module_name)
        module_name = module_path;
    else
        module_name += 1;

    FILEDLG95_MRU_get_slot(module_name, stored_path, NULL);
    TRACE("got MRU path: %s\n", wine_dbgstr_w(stored_path));
}

2420
void FILEDLG95_OnOpenMessage(HWND hwnd, int idCaption, int idText)
2421
{
2422 2423
  WCHAR strMsgTitle[MAX_PATH];
  WCHAR strMsgText [MAX_PATH];
2424
  if (idCaption)
2425
    LoadStringW(COMDLG32_hInstance, idCaption, strMsgTitle, ARRAY_SIZE(strMsgTitle));
2426 2427
  else
    strMsgTitle[0] = '\0';
2428
  LoadStringW(COMDLG32_hInstance, idText, strMsgText, ARRAY_SIZE(strMsgText));
2429
  MessageBoxW(hwnd,strMsgText, strMsgTitle, MB_OK | MB_ICONHAND);
2430 2431
}

2432 2433 2434 2435 2436 2437 2438 2439
int FILEDLG95_ValidatePathAction(LPWSTR lpstrPathAndFile, IShellFolder **ppsf,
                                 HWND hwnd, DWORD flags, BOOL isSaveDlg, int defAction)
{
    int nOpenAction = defAction;
    LPWSTR lpszTemp, lpszTemp1;
    LPITEMIDLIST pidl = NULL;

    /* check for invalid chars */
2440
    if((wcspbrk(lpstrPathAndFile+3, L"/:<>|") != NULL) && !(flags & OFN_NOVALIDATE))
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
    {
        FILEDLG95_OnOpenMessage(hwnd, IDS_INVALID_FILENAME_TITLE, IDS_INVALID_FILENAME);
        return FALSE;
    }

    if (FAILED (SHGetDesktopFolder(ppsf))) return FALSE;

    lpszTemp1 = lpszTemp = lpstrPathAndFile;
    while (lpszTemp1)
    {
        LPSHELLFOLDER lpsfChild;
        WCHAR lpwstrTemp[MAX_PATH];
        DWORD dwEaten, dwAttributes;
        LPWSTR p;

        lstrcpyW(lpwstrTemp, lpszTemp);
        p = PathFindNextComponentW(lpwstrTemp);

        if (!p) break; /* end of path */

        *p = 0;
        lpszTemp = lpszTemp + lstrlenW(lpwstrTemp);

        /* There are no wildcards when OFN_NOVALIDATE is set */
        if(*lpszTemp==0 && !(flags & OFN_NOVALIDATE))
        {
            /* if the last element is a wildcard do a search */
2468
            if(wcspbrk(lpszTemp1, L"*?") != NULL)
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
            {
                nOpenAction = ONOPEN_SEARCH;
                break;
            }
        }
        lpszTemp1 = lpszTemp;

        TRACE("parse now=%s next=%s sf=%p\n",debugstr_w(lpwstrTemp), debugstr_w(lpszTemp), *ppsf);

        /* append a backslash to drive letters */
        if(lstrlenW(lpwstrTemp)==2 && lpwstrTemp[1] == ':' &&
           ((lpwstrTemp[0] >= 'a' && lpwstrTemp[0] <= 'z') ||
            (lpwstrTemp[0] >= 'A' && lpwstrTemp[0] <= 'Z')))
        {
            PathAddBackslashW(lpwstrTemp);
        }

        dwAttributes = SFGAO_FOLDER;
        if(SUCCEEDED(IShellFolder_ParseDisplayName(*ppsf, hwnd, NULL, lpwstrTemp, &dwEaten, &pidl, &dwAttributes)))
        {
            /* the path component is valid, we have a pidl of the next path component */
            TRACE("parse OK attr=0x%08x pidl=%p\n", dwAttributes, pidl);
            if(dwAttributes & SFGAO_FOLDER)
            {
                if(FAILED(IShellFolder_BindToObject(*ppsf, pidl, 0, &IID_IShellFolder, (LPVOID*)&lpsfChild)))
                {
                    ERR("bind to failed\n"); /* should not fail */
                    break;
                }
                IShellFolder_Release(*ppsf);
                *ppsf = lpsfChild;
                lpsfChild = NULL;
            }
            else
            {
                TRACE("value\n");

                /* end dialog, return value */
                nOpenAction = ONOPEN_OPEN;
                break;
            }
2510
            ILFree(pidl);
2511 2512 2513 2514 2515
            pidl = NULL;
        }
        else if (!(flags & OFN_NOVALIDATE))
        {
            if(*lpszTemp ||	/* points to trailing null for last path element */
2516
               (lpwstrTemp[lstrlenW(lpwstrTemp)-1] == '\\')) /* or if last element ends in '\' */
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
            {
                if(flags & OFN_PATHMUSTEXIST)
                {
                    FILEDLG95_OnOpenMessage(hwnd, 0, IDS_PATHNOTEXISTING);
                    break;
                }
            }
            else
            {
                if( (flags & OFN_FILEMUSTEXIST) && !isSaveDlg )
                {
                    FILEDLG95_OnOpenMessage(hwnd, 0, IDS_FILENOTEXISTING);
                    break;
                }
            }
            /* change to the current folder */
            nOpenAction = ONOPEN_OPEN;
            break;
        }
        else
        {
            nOpenAction = ONOPEN_OPEN;
            break;
        }
    }
2542
    ILFree(pidl);
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553

    return nOpenAction;
}

/***********************************************************************
 *      FILEDLG95_OnOpen
 *
 * Ok button WM_COMMAND message handler
 *
 * If the function succeeds, the return value is nonzero.
 */
2554 2555
BOOL FILEDLG95_OnOpen(HWND hwnd)
{
2556
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
  LPWSTR lpstrFileList;
  UINT nFileCount = 0;
  UINT sizeUsed = 0;
  BOOL ret = TRUE;
  WCHAR lpstrPathAndFile[MAX_PATH];
  LPSHELLFOLDER lpsf = NULL;
  int nOpenAction;

  TRACE("hwnd=%p\n", hwnd);

2567 2568 2569 2570
  /* try to browse the selected item */
  if(BrowseSelectedFolder(hwnd))
      return FALSE;

2571
  /* get the files from the edit control */
2572
  nFileCount = FILEDLG95_FILENAME_GetFileNames(hwnd, &lpstrFileList, &sizeUsed);
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593

  if(nFileCount == 0)
      return FALSE;

  if(nFileCount > 1)
  {
      ret = FILEDLG95_OnOpenMultipleFiles(hwnd, lpstrFileList, nFileCount, sizeUsed);
      goto ret;
  }

  TRACE("count=%u len=%u file=%s\n", nFileCount, sizeUsed, debugstr_w(lpstrFileList));

/*
  Step 1:  Build a complete path name from the current folder and
  the filename or path in the edit box.
  Special cases:
  - the path in the edit box is a root path
    (with or without drive letter)
  - the edit box contains ".." (or a path with ".." in it)
*/

2594
  COMDLG32_GetCanonicalPath(fodInfos->ShellInfos.pidlAbsCurrent, lpstrFileList, lpstrPathAndFile);
2595
  heap_free(lpstrFileList);
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607

/*
  Step 2: here we have a cleaned up path

  We have to parse the path step by step to see if we have to browse
  to a folder if the path points to a directory or the last
  valid element is a directory.

  valid variables:
    lpstrPathAndFile: cleaned up path
 */

2608 2609 2610 2611 2612 2613
  if (nFileCount &&
      (fodInfos->ofnInfos->Flags & OFN_NOVALIDATE) &&
      !(fodInfos->ofnInfos->Flags & OFN_FILEMUSTEXIST))
    nOpenAction = ONOPEN_OPEN;
  else
    nOpenAction = ONOPEN_BROWSE;
2614

2615 2616 2617 2618 2619
  nOpenAction = FILEDLG95_ValidatePathAction(lpstrPathAndFile, &lpsf, hwnd,
                                             fodInfos->ofnInfos->Flags,
                                             fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG,
                                             nOpenAction);
  if(!nOpenAction)
2620
      goto ret;
2621

2622 2623
/*
  Step 3: here we have a cleaned up and validated path
2624

2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
  valid variables:
   lpsf:             ShellFolder bound to the rightmost valid path component
   lpstrPathAndFile: cleaned up path
   nOpenAction:      action to do
*/
  TRACE("end validate sf=%p\n", lpsf);

  switch(nOpenAction)
  {
    case ONOPEN_SEARCH:   /* set the current filter to the file mask and refresh */
      TRACE("ONOPEN_SEARCH %s\n", debugstr_w(lpstrPathAndFile));
      {
        int iPos;
        LPWSTR lpszTemp = PathFindFileNameW(lpstrPathAndFile);
        DWORD len;

        /* replace the current filter */
2642
        heap_free(fodInfos->ShellInfos.lpstrCurrentFilter);
2643
        len = lstrlenW(lpszTemp)+1;
2644
        fodInfos->ShellInfos.lpstrCurrentFilter = heap_alloc(len * sizeof(WCHAR));
2645
        lstrcpyW( fodInfos->ShellInfos.lpstrCurrentFilter, lpszTemp);
2646 2647 2648

        /* set the filter cb to the extension when possible */
        if(-1 < (iPos = FILEDLG95_FILETYPE_SearchExt(fodInfos->DlgInfos.hwndFileTypeCB, lpszTemp)))
2649
        SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_SETCURSEL, iPos, 0);
2650 2651 2652 2653 2654 2655
      }
      /* fall through */
    case ONOPEN_BROWSE:   /* browse to the highest folder we could bind to */
      TRACE("ONOPEN_BROWSE\n");
      {
	IPersistFolder2 * ppf2;
2656 2657 2658 2659 2660
        if(SUCCEEDED(IShellFolder_QueryInterface( lpsf, &IID_IPersistFolder2, (LPVOID*)&ppf2)))
        {
          LPITEMIDLIST pidlCurrent;
          IPersistFolder2_GetCurFolder(ppf2, &pidlCurrent);
          IPersistFolder2_Release(ppf2);
2661
          if (!ILIsEqual(pidlCurrent, fodInfos->ShellInfos.pidlAbsCurrent))
2662
	  {
2663 2664
            if (SUCCEEDED(IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser, pidlCurrent, SBSP_ABSOLUTE))
                && fodInfos->ofnInfos->Flags & OFN_EXPLORER)
2665 2666
            {
              SendCustomDlgNotificationMessage(hwnd, CDN_FOLDERCHANGE);
2667
              SendMessageA(fodInfos->DlgInfos.hwndFileName, WM_SETTEXT, 0, (LPARAM)"");
2668
            }
2669
	  }
2670
	  else if( nOpenAction == ONOPEN_SEARCH )
2671
	  {
2672 2673
            if (fodInfos->Shell.FOIShellView)
              IShellView_Refresh(fodInfos->Shell.FOIShellView);
2674
	  }
2675
          ILFree(pidlCurrent);
2676 2677
          if (filename_is_edit( fodInfos ))
              SendMessageW(fodInfos->DlgInfos.hwndFileName, EM_SETSEL, 0, -1);
2678 2679 2680 2681 2682 2683 2684
          else
          {
              HWND hwnd;

              hwnd = (HWND)SendMessageA(fodInfos->DlgInfos.hwndFileName, CBEM_GETEDITCONTROL, 0, 0);
              SendMessageW(hwnd, EM_SETSEL, 0, -1);
          }
2685 2686 2687 2688 2689 2690 2691
        }
      }
      ret = FALSE;
      break;
    case ONOPEN_OPEN:   /* fill in the return struct and close the dialog */
      TRACE("ONOPEN_OPEN %s\n", debugstr_w(lpstrPathAndFile));
      {
2692 2693
        WCHAR *ext = NULL;

2694
        /* update READONLY check box flag */
2695
	if ((SendMessageW(GetDlgItem(hwnd,IDC_OPENREADONLY),BM_GETCHECK,0,0) & 0x03) == BST_CHECKED)
2696 2697 2698 2699
	  fodInfos->ofnInfos->Flags |= OFN_READONLY;
	else
	  fodInfos->ofnInfos->Flags &= ~OFN_READONLY;

2700
        /* Attach the file extension with file name*/
2701
        ext = PathFindExtensionW(lpstrPathAndFile);
2702
        if (! *ext && fodInfos->defext)
2703
        {
2704 2705
            /* if no extension is specified with file name, then */
            /* attach the extension from file filter or default one */
2706
            
2707
            WCHAR *filterExt = NULL;
2708
            LPWSTR lpstrFilter = NULL;
2709
            int PathLength = lstrlenW(lpstrPathAndFile);
2710

2711 2712 2713
            /*Get the file extension from file type filter*/
            lpstrFilter = (LPWSTR) CBGetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB,
                                             fodInfos->ofnInfos->nFilterIndex-1);
2714

2715
            if (lpstrFilter != (LPWSTR)CB_ERR)  /* control is not empty */
2716
            {
2717
                WCHAR* filterSearchIndex;
2718
                filterExt = heap_alloc((lstrlenW(lpstrFilter) + 1) * sizeof(WCHAR));
2719
                lstrcpyW(filterExt, lpstrFilter);
2720 2721 2722 2723

                /* if a semicolon-separated list of file extensions was given, do not include the
                   semicolon or anything after it in the extension.
                   example: if filterExt was "*.abc;*.def", it will become "*.abc" */
2724
                filterSearchIndex = wcschr(filterExt, ';');
2725
                if (filterSearchIndex)
2726
                {
2727
                    filterSearchIndex[0] = '\0';
2728 2729
                }

2730
                /* find the file extension by searching for the first dot in filterExt */
2731
                /* strip the * or anything else from the extension, "*.abc" becomes "abc" */
2732
                /* if the extension is invalid or contains a glob, ignore it */
2733 2734
                filterSearchIndex = wcschr(filterExt, '.');
                if (filterSearchIndex++ && !wcschr(filterSearchIndex, '*') && !wcschr(filterSearchIndex, '?'))
2735
                {
2736
                    lstrcpyW(filterExt, filterSearchIndex);
2737 2738
                }
                else
2739
                {
2740
                    heap_free(filterExt);
2741 2742 2743
                    filterExt = NULL;
                }
            }
2744

2745 2746 2747
            if (!filterExt)
            {
                /* use the default file extension */
2748
                filterExt = heap_alloc((lstrlenW(fodInfos->defext) + 1) * sizeof(WCHAR));
2749
                lstrcpyW(filterExt, fodInfos->defext);
2750
            }
2751

2752
            if (*filterExt) /* ignore filterExt="" */
2753 2754
            {
                /* Attach the dot*/
2755
                lstrcatW(lpstrPathAndFile, L".");
2756
                /* Attach the extension */
2757
                lstrcatW(lpstrPathAndFile, filterExt);
2758
            }
2759

2760
            heap_free(filterExt);
2761

2762 2763 2764
            /* In Open dialog: if file does not exist try without extension */
            if (!(fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG) && !PathFileExistsW(lpstrPathAndFile))
                  lpstrPathAndFile[PathLength] = '\0';
2765

2766 2767 2768 2769 2770 2771 2772
            /* Set/clear the output OFN_EXTENSIONDIFFERENT flag */
            if (*ext)
                ext++;
            if (!lstrcmpiW(fodInfos->defext, ext))
                fodInfos->ofnInfos->Flags &= ~OFN_EXTENSIONDIFFERENT;
            else
                fodInfos->ofnInfos->Flags |= OFN_EXTENSIONDIFFERENT;
2773 2774
	}

2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
	/* In Save dialog: check if the file already exists */
	if (fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG
	    && fodInfos->ofnInfos->Flags & OFN_OVERWRITEPROMPT
	    && PathFileExistsW(lpstrPathAndFile))
	{
	  WCHAR lpstrOverwrite[100];
	  int answer;

	  LoadStringW(COMDLG32_hInstance, IDS_OVERWRITEFILE, lpstrOverwrite, 100);
	  answer = MessageBoxW(hwnd, lpstrOverwrite, fodInfos->title,
			       MB_YESNO | MB_ICONEXCLAMATION);
2786
	  if (answer == IDNO || answer == IDCANCEL)
2787 2788 2789 2790
	  {
	    ret = FALSE;
	    goto ret;
	  }
2791 2792
	}

2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
        /* In Open dialog: check if it should be created if it doesn't exist */
        if (!(fodInfos->DlgInfos.dwDlgProp & FODPROP_SAVEDLG)
            && fodInfos->ofnInfos->Flags & OFN_CREATEPROMPT
            && !PathFileExistsW(lpstrPathAndFile))
        {
          WCHAR lpstrCreate[100];
          int answer;

          LoadStringW(COMDLG32_hInstance, IDS_CREATEFILE, lpstrCreate, 100);
          answer = MessageBoxW(hwnd, lpstrCreate, fodInfos->title,
                               MB_YESNO | MB_ICONEXCLAMATION);
2804
          if (answer == IDNO || answer == IDCANCEL)
2805 2806 2807 2808 2809 2810
          {
            ret = FALSE;
            goto ret;
          }
        }

2811 2812
        /* Check that the size of the file does not exceed buffer size.
             (Allow for extra \0 if OFN_MULTISELECT is set.) */
2813
        if(lstrlenW(lpstrPathAndFile) < fodInfos->ofnInfos->nMaxFile -
2814 2815 2816 2817 2818 2819 2820 2821
            ((fodInfos->ofnInfos->Flags & OFN_ALLOWMULTISELECT) ? 1 : 0))
        {

          /* fill destination buffer */
          if (fodInfos->ofnInfos->lpstrFile)
          {
             if(fodInfos->unicode)
             {
Jacek Caban's avatar
Jacek Caban committed
2822
               LPOPENFILENAMEW ofn = fodInfos->ofnInfos;
2823

2824
               lstrcpynW(ofn->lpstrFile, lpstrPathAndFile, ofn->nMaxFile);
2825 2826 2827 2828 2829
               if (ofn->Flags & OFN_ALLOWMULTISELECT)
                 ofn->lpstrFile[lstrlenW(ofn->lpstrFile) + 1] = '\0';
             }
             else
             {
Jacek Caban's avatar
Jacek Caban committed
2830
               LPOPENFILENAMEA ofn = (LPOPENFILENAMEA)fodInfos->ofnInfos;
2831 2832 2833 2834 2835 2836 2837 2838

               WideCharToMultiByte(CP_ACP, 0, lpstrPathAndFile, -1,
                                   ofn->lpstrFile, ofn->nMaxFile, NULL, NULL);
               if (ofn->Flags & OFN_ALLOWMULTISELECT)
                 ofn->lpstrFile[lstrlenA(ofn->lpstrFile) + 1] = '\0';
             }
          }

2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
          if(fodInfos->unicode)
          {
              LPWSTR lpszTemp;

              /* set filename offset */
              lpszTemp = PathFindFileNameW(lpstrPathAndFile);
              fodInfos->ofnInfos->nFileOffset = (lpszTemp - lpstrPathAndFile);

              /* set extension offset */
              lpszTemp = PathFindExtensionW(lpstrPathAndFile);
              fodInfos->ofnInfos->nFileExtension = (*lpszTemp) ? (lpszTemp - lpstrPathAndFile) + 1 : 0;
          }
          else
          {
2853 2854 2855 2856 2857 2858
              LPSTR lpszTemp;
              CHAR tempFileA[MAX_PATH];

              /* avoid using fodInfos->ofnInfos->lpstrFile since it can be NULL */
              WideCharToMultiByte(CP_ACP, 0, lpstrPathAndFile, -1,
                                  tempFileA, sizeof(tempFileA), NULL, NULL);
2859 2860

              /* set filename offset */
2861 2862
              lpszTemp = PathFindFileNameA(tempFileA);
              fodInfos->ofnInfos->nFileOffset = (lpszTemp - tempFileA);
2863

2864
              /* set extension offset */
2865 2866
              lpszTemp = PathFindExtensionA(tempFileA);
              fodInfos->ofnInfos->nFileExtension = (*lpszTemp) ? (lpszTemp - tempFileA) + 1 : 0;
2867
          }
2868 2869 2870 2871 2872 2873 2874

          /* set the lpstrFileTitle */
          if(fodInfos->ofnInfos->lpstrFileTitle)
	  {
            LPWSTR lpstrFileTitle = PathFindFileNameW(lpstrPathAndFile);
            if(fodInfos->unicode)
            {
Jacek Caban's avatar
Jacek Caban committed
2875
              LPOPENFILENAMEW ofn = fodInfos->ofnInfos;
2876
	      lstrcpynW(ofn->lpstrFileTitle, lpstrFileTitle, ofn->nMaxFileTitle);
2877 2878 2879
            }
            else
            {
Jacek Caban's avatar
Jacek Caban committed
2880
              LPOPENFILENAMEA ofn = (LPOPENFILENAMEA)fodInfos->ofnInfos;
2881 2882 2883 2884 2885
              WideCharToMultiByte(CP_ACP, 0, lpstrFileTitle, -1,
                    ofn->lpstrFileTitle, ofn->nMaxFileTitle, NULL, NULL);
            }
	  }

2886 2887 2888
          /* copy currently selected filter to lpstrCustomFilter */
          if (fodInfos->ofnInfos->lpstrCustomFilter)
          {
Jacek Caban's avatar
Jacek Caban committed
2889
            LPOPENFILENAMEA ofn = (LPOPENFILENAMEA)fodInfos->ofnInfos;
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
            int len = WideCharToMultiByte(CP_ACP, 0, fodInfos->ShellInfos.lpstrCurrentFilter, -1,
                                          NULL, 0, NULL, NULL);
            if (len + strlen(ofn->lpstrCustomFilter) + 1 <= ofn->nMaxCustFilter)
            {
              LPSTR s = ofn->lpstrCustomFilter;
              s += strlen(ofn->lpstrCustomFilter)+1;
              WideCharToMultiByte(CP_ACP, 0, fodInfos->ShellInfos.lpstrCurrentFilter, -1,
                                  s, len, NULL, NULL);
            }
          }


2902 2903 2904
          if ( !FILEDLG95_SendFileOK(hwnd, fodInfos) )
	      goto ret;

2905 2906
          FILEDLG95_MRU_save_filename(lpstrPathAndFile);

2907 2908 2909 2910 2911 2912
          TRACE("close\n");
	  FILEDLG95_Clean(hwnd);
          ret = EndDialog(hwnd, TRUE);
	}
	else
        {
2913 2914
          WORD size;

2915
          size = lstrlenW(lpstrPathAndFile) + 1;
2916 2917 2918
          if (fodInfos->ofnInfos->Flags & OFN_ALLOWMULTISELECT)
             size += 1;
          /* return needed size in first two bytes of lpstrFile */
2919 2920
          if(fodInfos->ofnInfos->lpstrFile)
              *(WORD *)fodInfos->ofnInfos->lpstrFile = size;
2921 2922
          FILEDLG95_Clean(hwnd);
          ret = EndDialog(hwnd, FALSE);
2923
          COMDLG32_SetCommDlgExtendedError(FNERR_BUFFERTOOSMALL);
2924 2925 2926 2927
        }
      }
      break;
  }
2928

2929 2930 2931 2932
ret:
  if(lpsf) IShellFolder_Release(lpsf);
  return ret;
}
2933

2934
/***********************************************************************
2935
 *      FILEDLG95_SHELL_Init
2936
 *
2937
 * Initialisation of the shell objects
2938
 */
2939
static LRESULT FILEDLG95_SHELL_Init(HWND hwnd)
2940
{
2941
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
2942

2943
  TRACE("%p\n", hwnd);
2944

2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
  /*
   * Initialisation of the FileOpenDialogInfos structure
   */

  /* Shell */

  /*ShellInfos */
  fodInfos->ShellInfos.hwndOwner = hwnd;

  /* Disable multi-select if flag not set */
  if (!(fodInfos->ofnInfos->Flags & OFN_ALLOWMULTISELECT))
  {
     fodInfos->ShellInfos.folderSettings.fFlags |= FWF_SINGLESEL;
  }
  fodInfos->ShellInfos.folderSettings.fFlags |= FWF_AUTOARRANGE | FWF_ALIGNLEFT;
  fodInfos->ShellInfos.folderSettings.ViewMode = FVM_LIST;
2961

2962 2963 2964 2965 2966
  /* Construct the IShellBrowser interface */
  fodInfos->Shell.FOIShellBrowser = IShellBrowserImpl_Construct(hwnd);

  return NOERROR;
}
2967

2968
/***********************************************************************
2969 2970 2971 2972
 *      FILEDLG95_SHELL_ExecuteCommand
 *
 * Change the folder option and refresh the view
 * If the function succeeds, the return value is nonzero.
2973
 */
2974
static BOOL FILEDLG95_SHELL_ExecuteCommand(HWND hwnd, LPCSTR lpVerb)
2975
{
2976
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
2977
  IContextMenu * pcm;
2978

2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994
  TRACE("(%p,%p)\n", hwnd, lpVerb);

  if(SUCCEEDED(IShellView_GetItemObject(fodInfos->Shell.FOIShellView,
					SVGIO_BACKGROUND,
					&IID_IContextMenu,
					(LPVOID*)&pcm)))
  {
    CMINVOKECOMMANDINFO ci;
    ZeroMemory(&ci, sizeof(CMINVOKECOMMANDINFO));
    ci.cbSize = sizeof(CMINVOKECOMMANDINFO);
    ci.lpVerb = lpVerb;
    ci.hwnd = hwnd;

    IContextMenu_InvokeCommand(pcm, &ci);
    IContextMenu_Release(pcm);
  }
2995

2996 2997
  return FALSE;
}
2998

2999
/***********************************************************************
3000
 *      FILEDLG95_SHELL_UpFolder
3001
 *
3002 3003
 * Browse to the specified object
 * If the function succeeds, the return value is nonzero.
3004
 */
3005
static BOOL FILEDLG95_SHELL_UpFolder(HWND hwnd)
3006
{
3007
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3008

3009 3010 3011 3012 3013 3014
  TRACE("\n");

  if(SUCCEEDED(IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser,
                                          NULL,
                                          SBSP_PARENT)))
  {
3015 3016
    if(fodInfos->ofnInfos->Flags & OFN_EXPLORER)
        SendCustomDlgNotificationMessage(hwnd, CDN_FOLDERCHANGE);
3017
    return TRUE;
3018 3019
  }
  return FALSE;
3020 3021
}
/***********************************************************************
3022 3023 3024
 *      FILEDLG95_SHELL_Clean
 *
 * Cleans the memory used by shell objects
3025
 */
3026
static void FILEDLG95_SHELL_Clean(HWND hwnd)
3027
{
3028
    FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3029

3030
    TRACE("\n");
3031

3032
    ILFree(fodInfos->ShellInfos.pidlAbsCurrent);
3033

3034
    /* clean Shell interfaces */
3035 3036 3037 3038 3039
    if (fodInfos->Shell.FOIShellView)
    {
      IShellView_DestroyViewWindow(fodInfos->Shell.FOIShellView);
      IShellView_Release(fodInfos->Shell.FOIShellView);
    }
3040 3041
    if (fodInfos->Shell.FOIShellFolder)
      IShellFolder_Release(fodInfos->Shell.FOIShellFolder);
3042 3043 3044 3045
    IShellBrowser_Release(fodInfos->Shell.FOIShellBrowser);
    if (fodInfos->Shell.FOIDataObject)
      IDataObject_Release(fodInfos->Shell.FOIDataObject);
}
3046

3047
/***********************************************************************
3048
 *      FILEDLG95_FILETYPE_Init
3049
 *
3050
 * Initialisation of the file type combo box
3051
 */
3052
static HRESULT FILEDLG95_FILETYPE_Init(HWND hwnd)
3053
{
3054
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3055 3056
  int nFilters = 0;  /* number of filters */
  int nFilterIndexCB;
3057

3058
  TRACE("%p\n", hwnd);
3059

3060 3061 3062 3063 3064 3065 3066 3067 3068
  if(fodInfos->customfilter)
  {
      /* customfilter has one entry...  title\0ext\0
       * Set first entry of combo box item with customfilter
       */
      LPWSTR  lpstrExt;
      LPCWSTR lpstrPos = fodInfos->customfilter;

      /* Get the title */
3069
      lpstrPos += lstrlenW(fodInfos->customfilter) + 1;
3070 3071 3072

      /* Copy the extensions */
      if (! *lpstrPos) return E_FAIL;	/* malformed filter */
3073
      if (!(lpstrExt = heap_alloc((lstrlenW(lpstrPos)+1)*sizeof(WCHAR)))) return E_FAIL;
3074
      lstrcpyW(lpstrExt,lpstrPos);
3075 3076

      /* Add the item at the end of the combo */
3077 3078 3079
      SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_ADDSTRING, 0, (LPARAM)fodInfos->customfilter);
      SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_SETITEMDATA, nFilters, (LPARAM)lpstrExt);

3080 3081
      nFilters++;
  }
3082 3083 3084 3085 3086
  if(fodInfos->filter)
  {
    LPCWSTR lpstrPos = fodInfos->filter;

    for(;;)
3087
    {
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
      /* filter is a list...  title\0ext\0......\0\0
       * Set the combo item text to the title and the item data
       *  to the ext
       */
      LPCWSTR lpstrDisplay;
      LPWSTR lpstrExt;

      /* Get the title */
      if(! *lpstrPos) break;	/* end */
      lpstrDisplay = lpstrPos;
3098
      lpstrPos += lstrlenW(lpstrPos) + 1;
3099

3100
      SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_ADDSTRING, 0, (LPARAM)lpstrDisplay);
3101 3102 3103

      nFilters++;

3104
      /* Copy the extensions */
3105
      if (!(lpstrExt = heap_alloc((lstrlenW(lpstrPos)+1)*sizeof(WCHAR)))) return E_FAIL;
3106 3107
      lstrcpyW(lpstrExt,lpstrPos);
      lpstrPos += lstrlenW(lpstrPos) + 1;
3108 3109

      /* Add the item at the end of the combo */
3110
      SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_SETITEMDATA, nFilters - 1, (LPARAM)lpstrExt);
3111 3112 3113

      /* malformed filters are added anyway... */
      if (!*lpstrExt) break;
3114
    }
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
  }

  /*
   * Set the current filter to the one specified
   * in the initialisation structure
   */
  if (fodInfos->filter || fodInfos->customfilter)
  {
    LPWSTR lpstrFilter;

    /* Check to make sure our index isn't out of bounds. */
    if ( fodInfos->ofnInfos->nFilterIndex >
         nFilters - (fodInfos->customfilter == NULL ? 0 : 1) )
      fodInfos->ofnInfos->nFilterIndex = (fodInfos->customfilter == NULL ? 1 : 0);
3129 3130 3131 3132 3133

    /* set default filter index */
    if(fodInfos->ofnInfos->nFilterIndex == 0 && fodInfos->customfilter == NULL)
      fodInfos->ofnInfos->nFilterIndex = 1;

3134 3135 3136 3137
    /* calculate index of Combo Box item */
    nFilterIndexCB = fodInfos->ofnInfos->nFilterIndex;
    if (fodInfos->customfilter == NULL)
      nFilterIndexCB--;
3138

3139
    /* Set the current index selection. */
3140
    SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_SETCURSEL, nFilterIndexCB, 0);
3141 3142 3143

    /* Get the corresponding text string from the combo box. */
    lpstrFilter = (LPWSTR) CBGetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB,
3144
                                             nFilterIndexCB);
3145

Kevin Koltzau's avatar
Kevin Koltzau committed
3146
    if ((INT_PTR)lpstrFilter == CB_ERR)  /* control is empty */
3147 3148 3149
      lpstrFilter = NULL;

    if(lpstrFilter)
3150
    {
3151 3152
      DWORD len;
      CharLowerW(lpstrFilter); /* lowercase */
3153
      len = lstrlenW(lpstrFilter)+1;
3154
      fodInfos->ShellInfos.lpstrCurrentFilter = heap_alloc( len * sizeof(WCHAR) );
3155
      lstrcpyW(fodInfos->ShellInfos.lpstrCurrentFilter,lpstrFilter);
3156
    }
3157 3158
  } else
      fodInfos->ofnInfos->nFilterIndex = 0;
3159
  return S_OK;
3160
}
3161

3162
/***********************************************************************
3163 3164 3165 3166
 *      FILEDLG95_FILETYPE_OnCommand
 *
 * WM_COMMAND of the file type combo box
 * If the function succeeds, the return value is nonzero.
3167
 */
3168
static BOOL FILEDLG95_FILETYPE_OnCommand(HWND hwnd, WORD wNotifyCode)
3169
{
3170
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3171

3172 3173 3174 3175 3176 3177 3178
  switch(wNotifyCode)
  {
    case CBN_SELENDOK:
    {
      LPWSTR lpstrFilter;

      /* Get the current item of the filetype combo box */
3179
      int iItem = SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_GETCURSEL, 0, 0);
3180

3181 3182 3183
      /* set the current filter index */
      fodInfos->ofnInfos->nFilterIndex = iItem +
        (fodInfos->customfilter == NULL ? 1 : 0);
3184

3185
      /* Set the current filter with the current selection */
3186
      heap_free(fodInfos->ShellInfos.lpstrCurrentFilter);
3187 3188 3189

      lpstrFilter = (LPWSTR) CBGetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB,
                                             iItem);
Kevin Koltzau's avatar
Kevin Koltzau committed
3190
      if((INT_PTR)lpstrFilter != CB_ERR)
3191 3192 3193
      {
          DWORD len;
          CharLowerW(lpstrFilter); /* lowercase */
3194
          len = lstrlenW(lpstrFilter)+1;
3195
          fodInfos->ShellInfos.lpstrCurrentFilter = heap_alloc( len * sizeof(WCHAR) );
3196
          lstrcpyW(fodInfos->ShellInfos.lpstrCurrentFilter,lpstrFilter);
3197 3198
          if(fodInfos->ofnInfos->Flags & OFN_EXPLORER)
              SendCustomDlgNotificationMessage(hwnd,CDN_TYPECHANGE);
3199 3200 3201
      }

      /* Refresh the actual view to display the included items*/
3202 3203
      if (fodInfos->Shell.FOIShellView)
        IShellView_Refresh(fodInfos->Shell.FOIShellView);
3204
    }
3205 3206
  }
  return FALSE;
3207
}
3208 3209 3210
/***********************************************************************
 *      FILEDLG95_FILETYPE_SearchExt
 *
3211
 * searches for an extension in the filetype box
3212 3213 3214
 */
static int FILEDLG95_FILETYPE_SearchExt(HWND hwnd,LPCWSTR lpstrExt)
{
3215 3216 3217
  int i, iCount;

  iCount = SendMessageW(hwnd, CB_GETCOUNT, 0, 0);
3218 3219

  TRACE("%s\n", debugstr_w(lpstrExt));
3220

3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
  if(iCount != CB_ERR)
  {
    for(i=0;i<iCount;i++)
    {
      if(!lstrcmpiW(lpstrExt,(LPWSTR)CBGetItemDataPtr(hwnd,i)))
          return i;
    }
  }
  return -1;
}
3231

3232
/***********************************************************************
3233 3234 3235
 *      FILEDLG95_FILETYPE_Clean
 *
 * Clean the memory used by the filetype combo box
3236
 */
3237
static void FILEDLG95_FILETYPE_Clean(HWND hwnd)
3238
{
3239
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3240
  int iPos;
3241 3242 3243
  int iCount;

  iCount = SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_GETCOUNT, 0, 0);
3244 3245 3246 3247 3248 3249 3250 3251

  TRACE("\n");

  /* Delete each string of the combo and their associated data */
  if(iCount != CB_ERR)
  {
    for(iPos = iCount-1;iPos>=0;iPos--)
    {
3252
      heap_free((void *)CBGetItemDataPtr(fodInfos->DlgInfos.hwndFileTypeCB,iPos));
3253
      SendMessageW(fodInfos->DlgInfos.hwndFileTypeCB, CB_DELETESTRING, iPos, 0);
3254
    }
3255 3256
  }
  /* Current filter */
3257
  heap_free(fodInfos->ShellInfos.lpstrCurrentFilter);
3258 3259 3260
}

/***********************************************************************
3261 3262 3263
 *      FILEDLG95_LOOKIN_Init
 *
 * Initialisation of the look in combo box
3264
 */
3265 3266 3267 3268 3269 3270

/* Small helper function, to determine if the unixfs shell extension is rooted 
 * at the desktop. Copied from dlls/shell32/shfldr_unixfs.c. 
 */
static inline BOOL FILEDLG95_unixfs_is_rooted_at_desktop(void) {
    HKEY hKey;
3271 3272 3273 3274

    if (RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\NameSpace\\"
                "{9D20AAE8-0625-44B0-9CA7-71889C2254D9}", 0, KEY_READ, &hKey) != ERROR_SUCCESS)
3275
        return FALSE;
3276

3277 3278 3279 3280
    RegCloseKey(hKey);
    return TRUE;
}

3281
static void FILEDLG95_LOOKIN_Init(HWND hwndCombo)
3282
{
3283 3284 3285
  IShellFolder	*psfRoot, *psfDrives;
  IEnumIDList	*lpeRoot, *lpeDrives;
  LPITEMIDLIST	pidlDrives, pidlTmp, pidlTmp1, pidlAbsTmp;
3286 3287
  HDC hdc;
  TEXTMETRICW tm;
3288
  LookInInfos *liInfos = heap_alloc_zero(sizeof(*liInfos));
3289

3290
  TRACE("%p\n", hwndCombo);
3291

3292
  liInfos->iMaxIndentation = 0;
3293

3294
  SetPropA(hwndCombo, LookInInfosStr, liInfos);
3295

3296 3297 3298 3299 3300
  hdc = GetDC( hwndCombo );
  SelectObject( hdc, (HFONT)SendMessageW( hwndCombo, WM_GETFONT, 0, 0 ));
  GetTextMetricsW( hdc, &tm );
  ReleaseDC( hwndCombo, hdc );

3301
  /* set item height for both text field and listbox */
3302 3303
  SendMessageW(hwndCombo, CB_SETITEMHEIGHT, -1, max(tm.tmHeight, GetSystemMetrics(SM_CYSMICON)));
  SendMessageW(hwndCombo, CB_SETITEMHEIGHT, 0, max(tm.tmHeight, GetSystemMetrics(SM_CYSMICON)));
3304

3305
  /* Turn on the extended UI for the combo box like Windows does */
3306
  SendMessageW(hwndCombo, CB_SETEXTENDEDUI, TRUE, 0);
3307

3308 3309 3310
  /* Initialise data of Desktop folder */
  SHGetSpecialFolderLocation(0,CSIDL_DESKTOP,&pidlTmp);
  FILEDLG95_LOOKIN_AddItem(hwndCombo, pidlTmp,LISTEND);
3311
  ILFree(pidlTmp);
3312

3313
  SHGetSpecialFolderLocation(0,CSIDL_DRIVES,&pidlDrives);
3314

3315
  SHGetDesktopFolder(&psfRoot);
3316

3317 3318 3319 3320
  if (psfRoot)
  {
    /* enumerate the contents of the desktop */
    if(SUCCEEDED(IShellFolder_EnumObjects(psfRoot, hwndCombo, SHCONTF_FOLDERS, &lpeRoot)))
3321
    {
3322 3323 3324
      while (S_OK == IEnumIDList_Next(lpeRoot, 1, &pidlTmp, NULL))
      {
	FILEDLG95_LOOKIN_AddItem(hwndCombo, pidlTmp,LISTEND);
3325

3326 3327
	/* If the unixfs extension is rooted, we don't expand the drives by default */
	if (!FILEDLG95_unixfs_is_rooted_at_desktop()) 
3328
	{
3329
	  /* special handling for CSIDL_DRIVES */
3330
	  if (ILIsEqual(pidlTmp, pidlDrives))
3331
	  {
3332
	    if(SUCCEEDED(IShellFolder_BindToObject(psfRoot, pidlTmp, NULL, &IID_IShellFolder, (LPVOID*)&psfDrives)))
3333
	    {
3334 3335
	      /* enumerate the drives */
	      if(SUCCEEDED(IShellFolder_EnumObjects(psfDrives, hwndCombo,SHCONTF_FOLDERS, &lpeDrives)))
3336
	      {
3337 3338
	        while (S_OK == IEnumIDList_Next(lpeDrives, 1, &pidlTmp1, NULL))
	        {
3339
	          pidlAbsTmp = ILCombine(pidlTmp, pidlTmp1);
3340
	          FILEDLG95_LOOKIN_AddItem(hwndCombo, pidlAbsTmp,LISTEND);
3341 3342
	          ILFree(pidlAbsTmp);
	          ILFree(pidlTmp1);
3343 3344
	        }
	        IEnumIDList_Release(lpeDrives);
3345
	      }
3346
	      IShellFolder_Release(psfDrives);
3347 3348
	    }
	  }
3349
	}
3350

3351
        ILFree(pidlTmp);
3352 3353
      }
      IEnumIDList_Release(lpeRoot);
3354
    }
3355
    IShellFolder_Release(psfRoot);
3356 3357
  }

3358
  ILFree(pidlDrives);
3359 3360 3361
}

/***********************************************************************
3362 3363 3364
 *      FILEDLG95_LOOKIN_DrawItem
 *
 * WM_DRAWITEM message handler
3365
 */
3366
static LRESULT FILEDLG95_LOOKIN_DrawItem(LPDRAWITEMSTRUCT pDIStruct)
3367
{
3368 3369 3370 3371 3372
  COLORREF crWin = GetSysColor(COLOR_WINDOW);
  COLORREF crHighLight = GetSysColor(COLOR_HIGHLIGHT);
  COLORREF crText = GetSysColor(COLOR_WINDOWTEXT);
  RECT rectText;
  RECT rectIcon;
3373
  SHFILEINFOW sfi;
3374 3375
  HIMAGELIST ilItemImage;
  int iIndentation;
3376
  TEXTMETRICW tm;
3377
  LPSFOLDER tmpFolder;
3378 3379
  UINT shgfi_flags = SHGFI_PIDL | SHGFI_OPENICON | SHGFI_SYSICONINDEX | SHGFI_DISPLAYNAME;
  UINT icon_width, icon_height;
3380

3381
  TRACE("\n");
3382

3383 3384
  if(pDIStruct->itemID == -1)
    return 0;
3385

3386 3387 3388
  if(!(tmpFolder = (LPSFOLDER) CBGetItemDataPtr(pDIStruct->hwndItem,
                            pDIStruct->itemID)))
    return 0;
3389

3390

3391 3392 3393 3394 3395 3396 3397 3398 3399
  icon_width = GetSystemMetrics(SM_CXICON);
  icon_height = GetSystemMetrics(SM_CYICON);
  if (pDIStruct->rcItem.bottom - pDIStruct->rcItem.top < icon_height)
  {
      icon_width = GetSystemMetrics(SM_CXSMICON);
      icon_height = GetSystemMetrics(SM_CYSMICON);
      shgfi_flags |= SHGFI_SMALLICON;
  }

3400 3401
  ilItemImage = (HIMAGELIST) SHGetFileInfoW ((LPCWSTR) tmpFolder->pidlItem,
                                             0, &sfi, sizeof (sfi), shgfi_flags );
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421

  /* Is this item selected ? */
  if(pDIStruct->itemState & ODS_SELECTED)
  {
    SetTextColor(pDIStruct->hDC,(0x00FFFFFF & ~(crText)));
    SetBkColor(pDIStruct->hDC,crHighLight);
    FillRect(pDIStruct->hDC,&pDIStruct->rcItem,GetSysColorBrush(COLOR_HIGHLIGHT));
  }
  else
  {
    SetTextColor(pDIStruct->hDC,crText);
    SetBkColor(pDIStruct->hDC,crWin);
    FillRect(pDIStruct->hDC,&pDIStruct->rcItem,GetSysColorBrush(COLOR_WINDOW));
  }

  /* Do not indent item if drawing in the edit of the combo */
  if(pDIStruct->itemState & ODS_COMBOBOXEDIT)
    iIndentation = 0;
  else
    iIndentation = tmpFolder->m_iIndent;
3422

3423 3424 3425
  /* Draw text and icon */

  /* Initialise the icon display area */
3426 3427 3428 3429
  rectIcon.left = pDIStruct->rcItem.left + 1 + icon_width/2 * iIndentation;
  rectIcon.top = (pDIStruct->rcItem.top + pDIStruct->rcItem.bottom - icon_height) / 2;
  rectIcon.right = rectIcon.left + icon_width + XTEXTOFFSET;
  rectIcon.bottom = (pDIStruct->rcItem.top + pDIStruct->rcItem.bottom + icon_height) / 2;
3430 3431

  /* Initialise the text display area */
3432
  GetTextMetricsW(pDIStruct->hDC, &tm);
3433 3434 3435
  rectText.left = rectIcon.right;
  rectText.top =
	  (pDIStruct->rcItem.top + pDIStruct->rcItem.bottom - tm.tmHeight) / 2;
3436
  rectText.right = pDIStruct->rcItem.right;
3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448
  rectText.bottom =
	  (pDIStruct->rcItem.top + pDIStruct->rcItem.bottom + tm.tmHeight) / 2;

  /* Draw the icon from the image list */
  ImageList_Draw(ilItemImage,
                 sfi.iIcon,
                 pDIStruct->hDC,
                 rectIcon.left,
                 rectIcon.top,
                 ILD_TRANSPARENT );

  /* Draw the associated text */
3449
  TextOutW(pDIStruct->hDC,rectText.left,rectText.top,sfi.szDisplayName,lstrlenW(sfi.szDisplayName));
3450
  return NOERROR;
3451 3452 3453
}

/***********************************************************************
3454 3455 3456 3457
 *      FILEDLG95_LOOKIN_OnCommand
 *
 * LookIn combo box WM_COMMAND message handler
 * If the function succeeds, the return value is nonzero.
3458
 */
3459
static BOOL FILEDLG95_LOOKIN_OnCommand(HWND hwnd, WORD wNotifyCode)
3460
{
3461
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3462 3463 3464 3465 3466 3467

  TRACE("%p\n", fodInfos);

  switch(wNotifyCode)
  {
    case CBN_SELENDOK:
3468
    {
3469 3470 3471
      LPSFOLDER tmpFolder;
      int iItem;

3472
      iItem = SendMessageW(fodInfos->DlgInfos.hwndLookInCB, CB_GETCURSEL, 0, 0);
3473

3474 3475
      if( iItem == CB_ERR) return FALSE;

3476 3477 3478 3479 3480 3481 3482 3483 3484
      if(!(tmpFolder = (LPSFOLDER) CBGetItemDataPtr(fodInfos->DlgInfos.hwndLookInCB,
                                               iItem)))
	return FALSE;


      if(SUCCEEDED(IShellBrowser_BrowseObject(fodInfos->Shell.FOIShellBrowser,
                                              tmpFolder->pidlItem,
                                              SBSP_ABSOLUTE)))
      {
3485 3486
        if(fodInfos->ofnInfos->Flags & OFN_EXPLORER)
            SendCustomDlgNotificationMessage(hwnd, CDN_FOLDERCHANGE);
3487 3488 3489
        return TRUE;
      }
      break;
3490 3491
    }

3492 3493 3494
  }
  return FALSE;
}
3495 3496

/***********************************************************************
3497 3498 3499 3500
 *      FILEDLG95_LOOKIN_AddItem
 *
 * Adds an absolute pidl item to the lookin combo box
 * returns the index of the inserted item
3501
 */
3502
static int FILEDLG95_LOOKIN_AddItem(HWND hwnd,LPITEMIDLIST pidl, int iInsertId)
3503
{
3504
  LPITEMIDLIST pidlNext;
3505
  SHFILEINFOW sfi;
3506 3507 3508
  SFOLDER *tmpFolder;
  LookInInfos *liInfos;

3509
  TRACE("%p, %p, %d\n", hwnd, pidl, iInsertId);
3510 3511 3512 3513

  if(!pidl)
    return -1;

3514
  if(!(liInfos = GetPropA(hwnd,LookInInfosStr)))
3515 3516
    return -1;

3517
  tmpFolder = heap_alloc_zero(sizeof(*tmpFolder));
3518 3519 3520 3521
  tmpFolder->m_iIndent = 0;

  /* Calculate the indentation of the item in the lookin*/
  pidlNext = pidl;
3522
  while ((pidlNext = ILGetNext(pidlNext)))
3523 3524 3525 3526
  {
    tmpFolder->m_iIndent++;
  }

3527
  tmpFolder->pidlItem = ILClone(pidl);
3528 3529 3530 3531 3532

  if(tmpFolder->m_iIndent > liInfos->iMaxIndentation)
    liInfos->iMaxIndentation = tmpFolder->m_iIndent;

  sfi.dwAttributes = SFGAO_FILESYSANCESTOR | SFGAO_FILESYSTEM;
3533
  SHGetFileInfoW((LPCWSTR)pidl,
3534 3535 3536
                  0,
                  &sfi,
                  sizeof(sfi),
3537
                  SHGFI_DISPLAYNAME | SHGFI_PIDL | SHGFI_ATTRIBUTES | SHGFI_ATTR_SPECIFIED);
3538

3539
  TRACE("-- Add %s attr=0x%08x\n", debugstr_w(sfi.szDisplayName), sfi.dwAttributes);
3540 3541 3542 3543 3544

  if((sfi.dwAttributes & SFGAO_FILESYSANCESTOR) || (sfi.dwAttributes & SFGAO_FILESYSTEM))
  {
    int iItemID;

3545
    TRACE("-- Add %s at %u\n", debugstr_w(sfi.szDisplayName), tmpFolder->m_iIndent);
3546 3547 3548

    /* Add the item at the end of the list */
    if(iInsertId < 0)
3549
    {
3550
      iItemID = SendMessageW(hwnd, CB_ADDSTRING, 0, (LPARAM)sfi.szDisplayName);
3551
    }
3552 3553
    /* Insert the item at the iInsertId position*/
    else
3554
    {
3555
      iItemID = SendMessageW(hwnd, CB_INSERTSTRING, iInsertId, (LPARAM)sfi.szDisplayName);
3556
    }
3557

3558
    SendMessageW(hwnd, CB_SETITEMDATA, iItemID, (LPARAM)tmpFolder);
3559
    return iItemID;
3560
  }
3561

3562
  ILFree( tmpFolder->pidlItem );
3563
  heap_free( tmpFolder );
3564
  return -1;
3565

3566
}
3567 3568

/***********************************************************************
3569 3570 3571
 *      FILEDLG95_LOOKIN_InsertItemAfterParent
 *
 * Insert an item below its parent
3572
 */
3573
static int FILEDLG95_LOOKIN_InsertItemAfterParent(HWND hwnd,LPITEMIDLIST pidl)
3574 3575
{

3576 3577 3578 3579 3580
  LPITEMIDLIST pidlParent = GetParentPidl(pidl);
  int iParentPos;

  TRACE("\n");

3581 3582 3583
  if (pidl == pidlParent)
    return -1;

3584 3585 3586 3587 3588 3589 3590
  iParentPos = FILEDLG95_LOOKIN_SearchItem(hwnd,(WPARAM)pidlParent,SEARCH_PIDL);

  if(iParentPos < 0)
  {
    iParentPos = FILEDLG95_LOOKIN_InsertItemAfterParent(hwnd,pidlParent);
  }

3591
  ILFree(pidlParent);
3592

3593 3594
  return FILEDLG95_LOOKIN_AddItem(hwnd,pidl,iParentPos + 1);
}
3595

3596
/***********************************************************************
3597 3598 3599 3600
 *      FILEDLG95_LOOKIN_SelectItem
 *
 * Adds an absolute pidl item to the lookin combo box
 * returns the index of the inserted item
3601
 */
3602
int FILEDLG95_LOOKIN_SelectItem(HWND hwnd,LPITEMIDLIST pidl)
3603
{
3604 3605
  int iItemPos;
  LookInInfos *liInfos;
3606

3607
  TRACE("%p, %p\n", hwnd, pidl);
3608

3609 3610
  iItemPos = FILEDLG95_LOOKIN_SearchItem(hwnd,(WPARAM)pidl,SEARCH_PIDL);

3611
  liInfos = GetPropA(hwnd,LookInInfosStr);
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622

  if(iItemPos < 0)
  {
    while(FILEDLG95_LOOKIN_RemoveMostExpandedItem(hwnd) > -1);
    iItemPos = FILEDLG95_LOOKIN_InsertItemAfterParent(hwnd,pidl);
  }

  else
  {
    SFOLDER *tmpFolder = (LPSFOLDER) CBGetItemDataPtr(hwnd,iItemPos);
    while(liInfos->iMaxIndentation > tmpFolder->m_iIndent)
3623
    {
3624 3625 3626 3627 3628 3629
      int iRemovedItem;

      if(-1 == (iRemovedItem = FILEDLG95_LOOKIN_RemoveMostExpandedItem(hwnd)))
        break;
      if(iRemovedItem < iItemPos)
        iItemPos--;
3630
    }
3631 3632
  }

3633
  SendMessageW(hwnd, CB_SETCURSEL, iItemPos, 0);
3634 3635 3636 3637
  liInfos->uSelectedItem = iItemPos;

  return 0;

3638
}
3639

3640
/***********************************************************************
3641 3642 3643
 *      FILEDLG95_LOOKIN_RemoveMostExpandedItem
 *
 * Remove the item with an expansion level over iExpansionLevel
3644
 */
3645
static int FILEDLG95_LOOKIN_RemoveMostExpandedItem(HWND hwnd)
3646
{
3647
  int iItemPos;
3648
  LookInInfos *liInfos = GetPropA(hwnd,LookInInfosStr);
3649

3650
  TRACE("\n");
3651

3652 3653
  if(liInfos->iMaxIndentation <= 2)
    return -1;
3654

3655
  if((iItemPos = FILEDLG95_LOOKIN_SearchItem(hwnd,liInfos->iMaxIndentation,SEARCH_EXP)) >=0)
3656 3657
  {
    SFOLDER *tmpFolder = (LPSFOLDER) CBGetItemDataPtr(hwnd,iItemPos);
3658
    ILFree(tmpFolder->pidlItem);
3659
    heap_free(tmpFolder);
3660
    SendMessageW(hwnd, CB_DELETESTRING, iItemPos, 0);
3661
    liInfos->iMaxIndentation--;
3662

3663 3664
    return iItemPos;
  }
3665

3666 3667
  return -1;
}
3668

3669 3670 3671 3672 3673 3674 3675 3676 3677
/***********************************************************************
 *      FILEDLG95_LOOKIN_SearchItem
 *
 * Search for pidl in the lookin combo box
 * returns the index of the found item
 */
static int FILEDLG95_LOOKIN_SearchItem(HWND hwnd,WPARAM searchArg,int iSearchMethod)
{
  int i = 0;
3678 3679 3680
  int iCount;

  iCount = SendMessageW(hwnd, CB_GETCOUNT, 0, 0);
3681

3682
  TRACE("0x%08lx 0x%x\n",searchArg, iSearchMethod);
3683

3684 3685 3686
  if (iCount != CB_ERR)
  {
    for(;i<iCount;i++)
3687
    {
3688
      LPSFOLDER tmpFolder = (LPSFOLDER) CBGetItemDataPtr(hwnd,i);
3689

3690
      if (iSearchMethod == SEARCH_PIDL && ILIsEqual((LPITEMIDLIST)searchArg, tmpFolder->pidlItem))
3691 3692 3693
        return i;
      if(iSearchMethod == SEARCH_EXP && tmpFolder->m_iIndent == (int)searchArg)
        return i;
3694
    }
3695 3696 3697
  }

  return -1;
3698 3699 3700
}

/***********************************************************************
3701 3702 3703
 *      FILEDLG95_LOOKIN_Clean
 *
 * Clean the memory used by the lookin combo box
3704
 */
3705
static void FILEDLG95_LOOKIN_Clean(HWND hwnd)
3706
{
3707
    FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3708
    LookInInfos *liInfos = GetPropA(fodInfos->DlgInfos.hwndLookInCB,LookInInfosStr);
3709 3710 3711
    int iPos, iCount;

    iCount = SendMessageW(fodInfos->DlgInfos.hwndLookInCB, CB_GETCOUNT, 0, 0);
3712

3713
    TRACE("\n");
3714

3715 3716
    /* Delete each string of the combo and their associated data */
    if (iCount != CB_ERR)
3717
    {
3718 3719 3720
      for(iPos = iCount-1;iPos>=0;iPos--)
      {
        SFOLDER *tmpFolder = (LPSFOLDER) CBGetItemDataPtr(fodInfos->DlgInfos.hwndLookInCB,iPos);
3721
        ILFree(tmpFolder->pidlItem);
3722
        heap_free(tmpFolder);
3723
        SendMessageW(fodInfos->DlgInfos.hwndLookInCB, CB_DELETESTRING, iPos, 0);
3724
      }
3725 3726
    }

3727
    /* LookInInfos structure */
3728
    heap_free(liInfos);
3729
    RemovePropA(fodInfos->DlgInfos.hwndLookInCB,LookInInfosStr);
3730
}
3731

3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750
/***********************************************************************
 *          get_def_format
 *
 * Fill the FORMATETC used in the shell id list
 */
static FORMATETC get_def_format(void)
{
    static CLIPFORMAT cfFormat;
    FORMATETC formatetc;

    if (!cfFormat) cfFormat = RegisterClipboardFormatA(CFSTR_SHELLIDLISTA);
    formatetc.cfFormat = cfFormat;
    formatetc.ptd = 0;
    formatetc.dwAspect = DVASPECT_CONTENT;
    formatetc.lindex = -1;
    formatetc.tymed = TYMED_HGLOBAL;
    return formatetc;
}

3751
/***********************************************************************
3752 3753 3754
 * FILEDLG95_FILENAME_FillFromSelection
 *
 * fills the edit box from the cached DataObject
3755
 */
3756
void FILEDLG95_FILENAME_FillFromSelection (HWND hwnd)
3757
{
3758
    FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3759
    LPITEMIDLIST      pidl;
3760 3761
    LPWSTR            lpstrAllFiles, lpstrTmp;
    UINT nFiles = 0, nFileToOpen, nFileSelected, nAllFilesLength = 0, nThisFileLength, nAllFilesMaxLength;
3762 3763 3764
    STGMEDIUM medium;
    LPIDA cida;
    FORMATETC formatetc = get_def_format();
3765

3766
    TRACE("\n");
3767

3768 3769 3770 3771 3772
    if (FAILED(IDataObject_GetData(fodInfos->Shell.FOIDataObject, &formatetc, &medium)))
        return;

    cida = GlobalLock(medium.u.hGlobal);
    nFileSelected = cida->cidl;
3773

3774 3775
    /* Allocate a buffer */
    nAllFilesMaxLength = MAX_PATH + 3;
3776
    lpstrAllFiles = heap_alloc_zero(nAllFilesMaxLength * sizeof(WCHAR));
3777 3778 3779 3780 3781
    if (!lpstrAllFiles)
        goto ret;

    /* Loop through the selection, handle only files (not folders) */
    for (nFileToOpen = 0; nFileToOpen < nFileSelected; nFileToOpen++)
3782
    {
3783
        pidl = (LPITEMIDLIST)((LPBYTE)cida + cida->aoffset[nFileToOpen + 1]);
3784
        if (pidl)
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804
        {
            if (!IsPidlFolder(fodInfos->Shell.FOIShellFolder, pidl))
            {
                if (nAllFilesLength + MAX_PATH + 3 > nAllFilesMaxLength)
                {
                    nAllFilesMaxLength *= 2;
                    lpstrTmp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpstrAllFiles, nAllFilesMaxLength * sizeof(WCHAR));
                    if (!lpstrTmp)
                        goto ret;
                    lpstrAllFiles = lpstrTmp;
                }
                nFiles += 1;
                lpstrAllFiles[nAllFilesLength++] = '"';
                GetName(fodInfos->Shell.FOIShellFolder, pidl, SHGDN_INFOLDER | SHGDN_FORPARSING, lpstrAllFiles + nAllFilesLength);
                nThisFileLength = lstrlenW(lpstrAllFiles + nAllFilesLength);
                nAllFilesLength += nThisFileLength;
                lpstrAllFiles[nAllFilesLength++] = '"';
                lpstrAllFiles[nAllFilesLength++] = ' ';
            }
        }
3805
    }
3806

3807
    if (nFiles != 0)
3808
    {
3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
        /* If there's only one file, use the name as-is without quotes */
        lpstrTmp = lpstrAllFiles;
        if (nFiles == 1)
        {
            lpstrTmp += 1;
            lpstrTmp[nThisFileLength] = 0;
        }
        SetWindowTextW(fodInfos->DlgInfos.hwndFileName, lpstrTmp);
        /* Select the file name like Windows does */
        if (filename_is_edit(fodInfos))
            SendMessageW(fodInfos->DlgInfos.hwndFileName, EM_SETSEL, 0, -1);
3820
    }
3821 3822

ret:
3823
    heap_free(lpstrAllFiles);
3824
    COMCTL32_ReleaseStgMedium(medium);
3825
}
3826

3827

3828
/* copied from shell32 to avoid linking to it
3829 3830
 * Although shell32 is already linked the behaviour of exported StrRetToStrN
 * is dependent on whether emulated OS is unicode or not.
3831
 */
3832
static HRESULT COMDLG32_StrRetToStrNW (LPWSTR dest, DWORD len, LPSTRRET src, const ITEMIDLIST *pidl)
3833 3834 3835 3836
{
	switch (src->uType)
	{
	  case STRRET_WSTR:
3837
	    lstrcpynW(dest, src->u.pOleStr, len);
3838
	    CoTaskMemFree(src->u.pOleStr);
3839 3840 3841
	    break;

	  case STRRET_CSTR:
3842 3843
            if (!MultiByteToWideChar( CP_ACP, 0, src->u.cStr, -1, dest, len ) && len)
                  dest[len-1] = 0;
3844 3845 3846
	    break;

	  case STRRET_OFFSET:
3847 3848
            if (!MultiByteToWideChar( CP_ACP, 0, ((LPCSTR)&pidl->mkid)+src->u.uOffset, -1, dest, len ) && len)
                  dest[len-1] = 0;
3849 3850 3851
	    break;

	  default:
3852 3853 3854
	    FIXME("unknown type %x!\n", src->uType);
	    if (len) *dest = '\0';
	    return E_FAIL;
3855 3856
	}
	return S_OK;
3857 3858 3859
}

/***********************************************************************
3860 3861
 * FILEDLG95_FILENAME_GetFileNames
 *
3862
 * Copies the filenames to a delimited string list.
3863
 */
3864
static int FILEDLG95_FILENAME_GetFileNames (HWND hwnd, LPWSTR * lpstrFileList, UINT * sizeUsed)
3865
{
3866
	FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
3867 3868 3869
	UINT nFileCount = 0;	/* number of files */
	UINT nStrLen = 0;	/* length of string in edit control */
	LPWSTR lpstrEdit;	/* buffer for string from edit control */
3870

3871
	TRACE("\n");
3872

3873 3874
	/* get the filenames from the filename control */
	nStrLen = GetWindowTextLengthW( fodInfos->DlgInfos.hwndFileName );
3875
	lpstrEdit = heap_alloc( (nStrLen+1)*sizeof(WCHAR) );
3876
	GetWindowTextW( fodInfos->DlgInfos.hwndFileName, lpstrEdit, nStrLen+1);
3877

3878
	TRACE("nStrLen=%u str=%s\n", nStrLen, debugstr_w(lpstrEdit));
3879

3880
	nFileCount = COMDLG32_SplitFileNames(lpstrEdit, nStrLen, lpstrFileList, sizeUsed);
3881
	heap_free(lpstrEdit);
3882
	return nFileCount;
3883
}
3884

3885 3886 3887 3888
/*
 * DATAOBJECT Helper functions
 */

3889
/***********************************************************************
3890 3891 3892
 * COMCTL32_ReleaseStgMedium
 *
 * like ReleaseStgMedium from ole32
3893
 */
3894
static void COMCTL32_ReleaseStgMedium (STGMEDIUM medium)
3895
{
3896 3897 3898 3899 3900 3901 3902 3903 3904
      if(medium.pUnkForRelease)
      {
        IUnknown_Release(medium.pUnkForRelease);
      }
      else
      {
        GlobalUnlock(medium.u.hGlobal);
        GlobalFree(medium.u.hGlobal);
      }
3905 3906
}

3907 3908 3909 3910 3911 3912
/***********************************************************************
 *          GetPidlFromDataObject
 *
 * Return pidl(s) by number from the cached DataObject
 *
 * nPidlIndex=0 gets the fully qualified root path
3913
 */
3914
LPITEMIDLIST GetPidlFromDataObject ( IDataObject *doSelected, UINT nPidlIndex)
3915 3916
{

3917
    STGMEDIUM medium;
3918
    FORMATETC formatetc = get_def_format();
3919
    LPITEMIDLIST pidl = NULL;
3920

3921
    TRACE("sv=%p index=%u\n", doSelected, nPidlIndex);
3922

3923 3924
    if (!doSelected)
        return NULL;
3925

3926 3927
    /* Get the pidls from IDataObject */
    if(SUCCEEDED(IDataObject_GetData(doSelected,&formatetc,&medium)))
3928
    {
3929 3930 3931
      LPIDA cida = GlobalLock(medium.u.hGlobal);
      if(nPidlIndex <= cida->cidl)
      {
3932
        pidl = ILClone((LPITEMIDLIST)(&((LPBYTE)cida)[cida->aoffset[nPidlIndex]]));
3933 3934
      }
      COMCTL32_ReleaseStgMedium(medium);
3935
    }
3936
    return pidl;
3937
}
3938

3939 3940 3941 3942 3943 3944
/***********************************************************************
 *          GetNumSelected
 *
 * Return the number of selected items in the DataObject.
 *
*/
3945
static UINT GetNumSelected( IDataObject *doSelected )
3946
{
3947 3948
    UINT retVal = 0;
    STGMEDIUM medium;
3949
    FORMATETC formatetc = get_def_format();
3950 3951 3952 3953 3954 3955 3956

    TRACE("sv=%p\n", doSelected);

    if (!doSelected) return 0;

    /* Get the pidls from IDataObject */
    if(SUCCEEDED(IDataObject_GetData(doSelected,&formatetc,&medium)))
3957
    {
3958 3959 3960 3961
      LPIDA cida = GlobalLock(medium.u.hGlobal);
      retVal = cida->cidl;
      COMCTL32_ReleaseStgMedium(medium);
      return retVal;
3962
    }
3963
    return 0;
3964 3965
}

3966 3967 3968
/*
 * TOOLS
 */
3969

3970 3971 3972 3973 3974 3975 3976 3977
/***********************************************************************
 *      GetName
 *
 * Get the pidl's display name (relative to folder) and
 * put it in lpstrFileName.
 *
 * Return NOERROR on success,
 * E_FAIL otherwise
3978
 */
3979

3980
static HRESULT GetName(LPSHELLFOLDER lpsf, LPITEMIDLIST pidl,DWORD dwFlags,LPWSTR lpstrFileName)
3981
{
3982 3983
  STRRET str;
  HRESULT hRes;
3984

3985
  TRACE("sf=%p pidl=%p\n", lpsf, pidl);
3986

3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997
  if(!lpsf)
  {
    SHGetDesktopFolder(&lpsf);
    hRes = GetName(lpsf,pidl,dwFlags,lpstrFileName);
    IShellFolder_Release(lpsf);
    return hRes;
  }

  /* Get the display name of the pidl relative to the folder */
  if (SUCCEEDED(hRes = IShellFolder_GetDisplayNameOf(lpsf, pidl, dwFlags, &str)))
  {
3998
      return COMDLG32_StrRetToStrNW(lpstrFileName, MAX_PATH, &str, pidl);
3999 4000
  }
  return E_FAIL;
4001 4002
}

4003 4004 4005 4006 4007
/***********************************************************************
 *      GetShellFolderFromPidl
 *
 * pidlRel is the item pidl relative
 * Return the IShellFolder of the absolute pidl
4008
 */
4009
IShellFolder *GetShellFolderFromPidl(LPITEMIDLIST pidlAbs)
4010
{
4011
  IShellFolder *psf = NULL,*psfParent;
4012

4013
  TRACE("%p\n", pidlAbs);
4014

4015 4016 4017 4018
  if(SUCCEEDED(SHGetDesktopFolder(&psfParent)))
  {
    psf = psfParent;
    if(pidlAbs && pidlAbs->mkid.cb)
4019
    {
4020 4021 4022 4023 4024
      if(SUCCEEDED(IShellFolder_BindToObject(psfParent, pidlAbs, NULL, &IID_IShellFolder, (LPVOID*)&psf)))
      {
	IShellFolder_Release(psfParent);
        return psf;
      }
4025
    }
4026 4027 4028 4029
    /* return the desktop */
    return psfParent;
  }
  return NULL;
4030 4031 4032
}

/***********************************************************************
4033
 *      GetParentPidl
4034
 *
4035
 * Return the LPITEMIDLIST to the parent of the pidl in the list
4036
 */
4037
LPITEMIDLIST GetParentPidl(LPITEMIDLIST pidl)
4038
{
4039
  LPITEMIDLIST pidlParent;
4040

4041
  TRACE("%p\n", pidl);
4042

4043 4044
  pidlParent = ILClone(pidl);
  ILRemoveLastID(pidlParent);
4045

4046
  return pidlParent;
4047 4048 4049
}

/***********************************************************************
4050
 *      GetPidlFromName
4051
 *
4052 4053
 * returns the pidl of the file name relative to folder
 * NULL if an error occurred
4054
 */
4055
static LPITEMIDLIST GetPidlFromName(IShellFolder *lpsf,LPWSTR lpcstrFileName)
4056
{
4057 4058
  LPITEMIDLIST pidl = NULL;
  ULONG ulEaten;
4059

4060
  TRACE("sf=%p file=%s\n", lpsf, debugstr_w(lpcstrFileName));
4061

4062 4063 4064 4065 4066 4067 4068 4069
  if(!lpcstrFileName) return NULL;
  if(!*lpcstrFileName) return NULL;

  if(!lpsf)
  {
    if (SUCCEEDED(SHGetDesktopFolder(&lpsf))) {
        IShellFolder_ParseDisplayName(lpsf, 0, NULL, lpcstrFileName, &ulEaten, &pidl, NULL);
        IShellFolder_Release(lpsf);
4070
    }
4071 4072 4073 4074 4075 4076 4077 4078 4079 4080
  }
  else
  {
    IShellFolder_ParseDisplayName(lpsf, 0, NULL, lpcstrFileName, &ulEaten, &pidl, NULL);
  }
  return pidl;
}

/*
*/
4081
static BOOL IsPidlFolder (LPSHELLFOLDER psf, LPCITEMIDLIST pidl)
4082 4083 4084 4085 4086 4087 4088
{
	ULONG uAttr  = SFGAO_FOLDER | SFGAO_HASSUBFOLDER;
	HRESULT ret;

	TRACE("%p, %p\n", psf, pidl);

  	ret = IShellFolder_GetAttributesOf( psf, 1, &pidl, &uAttr );
4089

4090
	TRACE("-- 0x%08x 0x%08x\n", uAttr, ret);
4091 4092
	/* see documentation shell 4.1*/
        return uAttr & (SFGAO_FOLDER | SFGAO_HASSUBFOLDER);
4093 4094 4095
}

/***********************************************************************
4096
 *      BrowseSelectedFolder
4097
 */
4098
static BOOL BrowseSelectedFolder(HWND hwnd)
4099
{
4100
  FileOpenDlgInfos *fodInfos = get_filedlg_infoptr(hwnd);
4101
  BOOL bBrowseSelFolder = FALSE;
4102

4103
  TRACE("\n");
4104

4105 4106 4107
  if (GetNumSelected(fodInfos->Shell.FOIDataObject) == 1)
  {
      LPITEMIDLIST pidlSelection;
4108

4109 4110 4111 4112 4113 4114 4115
      /* get the file selected */
      pidlSelection  = GetPidlFromDataObject( fodInfos->Shell.FOIDataObject, 1);
      if (IsPidlFolder (fodInfos->Shell.FOIShellFolder, pidlSelection))
      {
          if ( FAILED( IShellBrowser_BrowseObject( fodInfos->Shell.FOIShellBrowser,
                         pidlSelection, SBSP_RELATIVE ) ) )
          {
4116
               WCHAR buf[64];
4117
               LoadStringW( COMDLG32_hInstance, IDS_PATHNOTEXISTING, buf, ARRAY_SIZE(buf));
4118
               MessageBoxW( hwnd, buf, fodInfos->title, MB_OK | MB_ICONEXCLAMATION );
4119
          }
4120
          bBrowseSelFolder = TRUE;
4121 4122
          if(fodInfos->ofnInfos->Flags & OFN_EXPLORER)
              SendCustomDlgNotificationMessage(hwnd,CDN_FOLDERCHANGE);
4123
      }
4124
      ILFree( pidlSelection );
4125
  }
4126

4127 4128 4129
  return bBrowseSelFolder;
}

4130 4131 4132 4133 4134 4135
static inline BOOL valid_struct_size( DWORD size )
{
    return (size == OPENFILENAME_SIZE_VERSION_400W) ||
        (size == sizeof( OPENFILENAMEW ));
}

4136 4137 4138 4139 4140 4141
static inline BOOL is_win16_looks(DWORD flags)
{
    return (flags & (OFN_ALLOWMULTISELECT|OFN_ENABLEHOOK|OFN_ENABLETEMPLATE) &&
            !(flags & OFN_EXPLORER));
}

4142
/* ------------------ APIs ---------------------- */
4143

4144
/***********************************************************************
4145
 *            GetOpenFileNameA  (COMDLG32.@)
4146 4147 4148 4149
 *
 * Creates a dialog box for the user to select a file to open.
 *
 * RETURNS
4150
 *    TRUE on success: user enters a valid file
4151 4152 4153
 *    FALSE on cancel, error, close or filename-does-not-fit-in-buffer.
 *
 */
4154
BOOL WINAPI GetOpenFileNameA(OPENFILENAMEA *ofn)
4155
{
4156
    TRACE("flags 0x%08x\n", ofn->Flags);
4157

4158 4159 4160 4161 4162 4163
    if (!valid_struct_size( ofn->lStructSize ))
    {
        COMDLG32_SetCommDlgExtendedError( CDERR_STRUCTSIZE );
        return FALSE;
    }

4164 4165 4166 4167
    /* OFN_FILEMUSTEXIST implies OFN_PATHMUSTEXIST */
    if (ofn->Flags & OFN_FILEMUSTEXIST)
        ofn->Flags |= OFN_PATHMUSTEXIST;

4168
    if (is_win16_looks(ofn->Flags))
4169 4170
        return GetFileName31A(ofn, OPEN_DIALOG);
    else
4171 4172 4173 4174 4175 4176
    {
        FileOpenDlgInfos info;

        init_filedlg_infoA(ofn, &info);
        return GetFileDialog95(&info, OPEN_DIALOG);
    }
4177
}
4178 4179

/***********************************************************************
4180
 *            GetOpenFileNameW (COMDLG32.@)
4181 4182 4183 4184
 *
 * Creates a dialog box for the user to select a file to open.
 *
 * RETURNS
4185
 *    TRUE on success: user enters a valid file
4186 4187 4188
 *    FALSE on cancel, error, close or filename-does-not-fit-in-buffer.
 *
 */
4189
BOOL WINAPI GetOpenFileNameW(OPENFILENAMEW *ofn)
4190
{
4191
    TRACE("flags 0x%08x\n", ofn->Flags);
4192

4193 4194 4195 4196 4197 4198
    if (!valid_struct_size( ofn->lStructSize ))
    {
        COMDLG32_SetCommDlgExtendedError( CDERR_STRUCTSIZE );
        return FALSE;
    }

4199 4200 4201 4202
    /* OFN_FILEMUSTEXIST implies OFN_PATHMUSTEXIST */
    if (ofn->Flags & OFN_FILEMUSTEXIST)
        ofn->Flags |= OFN_PATHMUSTEXIST;

4203
    if (is_win16_looks(ofn->Flags))
4204 4205
        return GetFileName31W(ofn, OPEN_DIALOG);
    else
4206 4207 4208 4209 4210 4211
    {
        FileOpenDlgInfos info;

        init_filedlg_infoW(ofn, &info);
        return GetFileDialog95(&info, OPEN_DIALOG);
    }
4212
}
4213

4214

4215
/***********************************************************************
4216
 *            GetSaveFileNameA  (COMDLG32.@)
4217 4218 4219 4220
 *
 * Creates a dialog box for the user to select a file to save.
 *
 * RETURNS
4221
 *    TRUE on success: user enters a valid file
4222 4223 4224
 *    FALSE on cancel, error, close or filename-does-not-fit-in-buffer.
 *
 */
4225
BOOL WINAPI GetSaveFileNameA(OPENFILENAMEA *ofn)
4226
{
4227 4228 4229 4230 4231 4232
    if (!valid_struct_size( ofn->lStructSize ))
    {
        COMDLG32_SetCommDlgExtendedError( CDERR_STRUCTSIZE );
        return FALSE;
    }

4233
    if (is_win16_looks(ofn->Flags))
4234 4235
        return GetFileName31A(ofn, SAVE_DIALOG);
    else
4236 4237 4238 4239 4240 4241
    {
        FileOpenDlgInfos info;

        init_filedlg_infoA(ofn, &info);
        return GetFileDialog95(&info, SAVE_DIALOG);
    }
4242 4243
}

4244
/***********************************************************************
4245
 *            GetSaveFileNameW  (COMDLG32.@)
4246 4247 4248 4249
 *
 * Creates a dialog box for the user to select a file to save.
 *
 * RETURNS
4250
 *    TRUE on success: user enters a valid file
4251 4252 4253 4254
 *    FALSE on cancel, error, close or filename-does-not-fit-in-buffer.
 *
 */
BOOL WINAPI GetSaveFileNameW(
4255
	LPOPENFILENAMEW ofn) /* [in/out] address of init structure */
4256
{
4257 4258 4259 4260 4261 4262
    if (!valid_struct_size( ofn->lStructSize ))
    {
        COMDLG32_SetCommDlgExtendedError( CDERR_STRUCTSIZE );
        return FALSE;
    }

4263
    if (is_win16_looks(ofn->Flags))
4264 4265
        return GetFileName31W(ofn, SAVE_DIALOG);
    else
4266 4267 4268 4269 4270 4271
    {
        FileOpenDlgInfos info;

        init_filedlg_infoW(ofn, &info);
        return GetFileDialog95(&info, SAVE_DIALOG);
    }
4272
}
4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285

/***********************************************************************
 *	GetFileTitleA		(COMDLG32.@)
 *
 * See GetFileTitleW.
 */
short WINAPI GetFileTitleA(LPCSTR lpFile, LPSTR lpTitle, WORD cbBuf)
{
    int ret;
    UNICODE_STRING strWFile;
    LPWSTR lpWTitle;

    RtlCreateUnicodeStringFromAsciiz(&strWFile, lpFile);
4286
    lpWTitle = heap_alloc(cbBuf * sizeof(WCHAR));
4287 4288 4289
    ret = GetFileTitleW(strWFile.Buffer, lpWTitle, cbBuf);
    if (!ret) WideCharToMultiByte( CP_ACP, 0, lpWTitle, -1, lpTitle, cbBuf, NULL, NULL );
    RtlFreeUnicodeString( &strWFile );
4290
    heap_free( lpWTitle );
4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316
    return ret;
}


/***********************************************************************
 *	GetFileTitleW		(COMDLG32.@)
 *
 * Get the name of a file.
 *
 * PARAMS
 *  lpFile  [I] name and location of file
 *  lpTitle [O] returned file name
 *  cbBuf   [I] buffer size of lpTitle
 *
 * RETURNS
 *  Success: zero
 *  Failure: negative number.
 */
short WINAPI GetFileTitleW(LPCWSTR lpFile, LPWSTR lpTitle, WORD cbBuf)
{
	int i, len;
	TRACE("(%p %p %d);\n", lpFile, lpTitle, cbBuf);

	if(lpFile == NULL || lpTitle == NULL)
		return -1;

4317
	len = lstrlenW(lpFile);
4318 4319 4320 4321

	if (len == 0)
		return -1;

4322
        if(wcspbrk(lpFile, L"*[]"))
4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341
		return -1;

	len--;

	if(lpFile[len] == '/' || lpFile[len] == '\\' || lpFile[len] == ':')
		return -1;

	for(i = len; i >= 0; i--)
	{
		if (lpFile[i] == '/' ||  lpFile[i] == '\\' ||  lpFile[i] == ':')
		{
			i++;
			break;
		}
	}

	if(i == -1)
		i++;

4342
	TRACE("---> %s\n", debugstr_w(&lpFile[i]));
4343

4344
	len = lstrlenW(lpFile+i)+1;
4345 4346 4347
	if(cbBuf < len)
		return len;

4348
	lstrcpyW(lpTitle, &lpFile[i]);
4349 4350
	return 0;
}