summaryrefslogtreecommitdiff
path: root/fpicker/source/win32/filepicker/WinFileOpenImpl.cxx
blob: c226fc415ca7ae55f7292572a72e9b5416a908d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
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
696
697
698
699
700
701
702
703
704
705
706
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
774
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "shared.hxx"
#include "WinFileOpenImpl.hxx"
#include <osl/diagnose.h>
#include <osl/file.hxx>
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/FilePickerEvent.hpp>
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#include "../misc/WinImplHelper.hxx"

#include "FilePicker.hxx"
#include "controlaccess.hxx"
#include "customcontrolfactory.hxx"
#include <rtl/ustrbuf.hxx>
#include <rtl/string.hxx>
#include <osl/thread.hxx>
#include "filepickerstate.hxx"


// namespace directives


using namespace com::sun::star;

using com::sun::star::ui::dialogs::FilePickerEvent;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::ui::dialogs::XFilePicker2;

using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::ListboxControlActions;


// to distinguish what to do in the enum child window callback function


enum ECW_ACTION_T
{
    INIT_CUSTOM_CONTROLS,
    CACHE_CONTROL_VALUES
};

struct EnumParam
{
    ECW_ACTION_T        m_action;
    CWinFileOpenImpl*   m_instance;

    EnumParam( ECW_ACTION_T action, CWinFileOpenImpl* instance ):
        m_action( action ),
        m_instance( instance )
    {}
};


// ctor


CWinFileOpenImpl::CWinFileOpenImpl(
    CFilePicker* aFilePicker,
    sal_Bool bFileOpenDialog,
    sal_uInt32 dwFlags,
    sal_uInt32 dwTemplateId,
    HINSTANCE hInstance) :
    CFileOpenDialog(bFileOpenDialog, dwFlags, dwTemplateId, hInstance),
    m_filterContainer(new CFilterContainer()),
    m_Preview(new CPreviewAdapter(hInstance)),
    m_CustomControls(CCustomControlFactory::CreateCustomControlContainer()),
    m_FilePicker(aFilePicker),
    m_bInitialSelChanged(sal_True),
    m_HelpPopupWindow(hInstance, m_hwndFileOpenDlg),
    m_ExecuteFilePickerState(new CExecuteFilePickerState()),
    m_NonExecuteFilePickerState(new CNonExecuteFilePickerState())
{
    m_FilePickerState = m_NonExecuteFilePickerState;
}


// dtor


CWinFileOpenImpl::~CWinFileOpenImpl()
{
    delete m_ExecuteFilePickerState;
    delete m_NonExecuteFilePickerState;
}


// we expect the directory in URL format


void CWinFileOpenImpl::setDisplayDirectory(const OUString& aDirectory)
    throw( IllegalArgumentException, uno::RuntimeException )
{
    OUString aSysDirectory;
    if( aDirectory.getLength() > 0)
    {
        if ( ::osl::FileBase::E_None !=
             ::osl::FileBase::getSystemPathFromFileURL(aDirectory,aSysDirectory))
            throw IllegalArgumentException(
                "Invalid directory",
                static_cast<XFilePicker2*>(m_FilePicker), 1);

        // we ensure that there is a trailing '/' at the end of
        // he given file url, because the windows functions only
        // works correctly when providing "c:\" or an environment
        // variable like "=c:=c:\.." etc. is set, else the
        // FolderPicker would stand in the root of the shell
        // hierarchy which is the desktop folder
        if ( aSysDirectory.lastIndexOf(BACKSLASH) != (aSysDirectory.getLength() - 1))
            aSysDirectory += BACKSLASH;
    }

    // call base class method
    CFileOpenDialog::setDisplayDirectory(aSysDirectory);
}


// we return the directory in URL format


OUString CWinFileOpenImpl::getDisplayDirectory() throw(uno::RuntimeException)
{
    return m_FilePickerState->getDisplayDirectory(this);
}


void SAL_CALL CWinFileOpenImpl::setDefaultName(const OUString& aName)
    throw( IllegalArgumentException, uno::RuntimeException )
{
    // we don't set the default name directly
    // because this influences how the file open
    // dialog sets the initial path when it is about
    // to open (see MSDN: OPENFILENAME)
    // so we save the default name which should
    // appear in the file-name-box and set
    // this name when processing onInitDone
    m_defaultName = aName;
}


// return format: URL
// if multiselection is allowed there are two different cases
// 1. one file selected: the sequence contains one entry path\filename.ext
// 2. multiple files selected: the sequence contains multiple entries
//    the first entry is the path url, all other entries are file names


uno::Sequence<OUString> SAL_CALL CWinFileOpenImpl::getFiles()
    throw(uno::RuntimeException)
{
    return m_FilePickerState->getFiles(this);
}


// shows the FileOpen/FileSave dialog


sal_Int16 SAL_CALL CWinFileOpenImpl::execute(  ) throw(uno::RuntimeException)
{
    sal_Int16 rc = CFileOpenDialog::doModal();

    if (1 == rc)
        rc = css::ui::dialogs::ExecutableDialogResults::OK;
    else if (0 == rc)
        rc = css::ui::dialogs::ExecutableDialogResults::CANCEL;
    else
        throw uno::RuntimeException(
            "Error executing dialog",
            static_cast<XFilePicker2*>(m_FilePicker));

    return rc;
}


// appends a new filter
// returns false if the title (aTitle) was already added or the title or the filter are
// empty


void SAL_CALL CWinFileOpenImpl::appendFilter(const OUString& aTitle, const OUString& aFilter)
    throw(IllegalArgumentException, uno::RuntimeException)
{
    sal_Bool bRet = m_filterContainer->addFilter(aTitle, aFilter);

    if (!bRet)
        throw IllegalArgumentException(
            "filter already exists",
            static_cast<XFilePicker2*>(m_FilePicker), 1);

    // #95345# see MSDN OPENFILENAME
    // If nFilterIndex is zero and lpstrCustomFilter is NULL,
    // the system uses the first filter in the lpstrFilter buffer.
    // to reflect this we must set the filter index so that calls
    // to getSelectedFilterIndex without explicitly calling
    // setFilterIndex before does not return 0 which leads to a
    // false state
    if (0 == getSelectedFilterIndex())
        CFileOpenDialog::setFilterIndex(1);
}


// sets a current filter


void SAL_CALL CWinFileOpenImpl::setCurrentFilter(const OUString& aTitle)
    throw( IllegalArgumentException, uno::RuntimeException)
{
    sal_Int32 filterPos = m_filterContainer->getFilterPos(aTitle);

    if (filterPos < 0)
        throw IllegalArgumentException(
            "filter doesn't exist",
            static_cast<XFilePicker2*>(m_FilePicker), 1);

    // filter index of the base class starts with 1
    CFileOpenDialog::setFilterIndex(filterPos + 1);
}


// returns the currently selected filter


OUString SAL_CALL CWinFileOpenImpl::getCurrentFilter() throw(uno::RuntimeException)
{
    sal_uInt32 nIndex = getSelectedFilterIndex();

    OUString currentFilter;
    if (nIndex > 0)
    {
        // filter index of the base class starts with 1
        if (!m_filterContainer->getFilter(nIndex - 1, currentFilter)) {
            OSL_ASSERT(false);
        }
    }

    return currentFilter;
}


inline void SAL_CALL CWinFileOpenImpl::appendFilterGroupSeparator()
{
    m_filterContainer->addFilter(FILTER_SEPARATOR, ALL_FILES_WILDCARD, ALLOW_DUPLICATES);
}


// XFilterGroupManager


void SAL_CALL CWinFileOpenImpl::appendFilterGroup(const OUString& sGroupTitle, const uno::Sequence<beans::StringPair>& aFilters)
    throw (IllegalArgumentException, uno::RuntimeException)
{
    (void) sGroupTitle; // avoid warning
    OSL_ENSURE(0 == sGroupTitle.getLength(), "appendFilterGroup: Parameter 'GroupTitle' currently ignored");

    sal_Int32 nFilters = aFilters.getLength();

    OSL_PRECOND(nFilters > 0, "Empty filter list");

    if (nFilters > 0)
    {
        // append a separator before the next group if
        // there is already a group of filters
        if (m_filterContainer->numFilter() > 0)
            appendFilterGroupSeparator();

        for (int i = 0; i < nFilters; i++)
            appendFilter(aFilters[i].First, aFilters[i].Second);
    }
}


// XExtendedFilePicker


// #i90917: Due to a different feature set for the system-dependent file pickers
// it's possible that generic code (e.g. sfx2) provides control ids
// (see ExtendedFilePickerElementIds::LISTBOX_FILTER_SELECTOR) which are NOT
// available on all platforms. This filter function should filter out control ids
// which are only available on KDE/GTK file pickers.
static bool filterControlCommand( sal_Int16 nControlId )
{
    if ( nControlId == LISTBOX_FILTER_SELECTOR )
        return true;
    return false;
}

void SAL_CALL CWinFileOpenImpl::setValue(sal_Int16 aControlId, sal_Int16 aControlAction, const uno::Any& aValue)
    throw(uno::RuntimeException)
{
    OSL_ASSERT(m_FilePickerState);
    if ( !filterControlCommand( aControlId ))
        m_FilePickerState->setValue(aControlId, aControlAction, aValue);
}


// returns the value of an custom template element
// we assume that there are only checkboxes or comboboxes


uno::Any SAL_CALL CWinFileOpenImpl::getValue(sal_Int16 aControlId, sal_Int16 aControlAction)
    throw(uno::RuntimeException)
{
    OSL_ASSERT(m_FilePickerState);
    if ( !filterControlCommand( aControlId ))
        return m_FilePickerState->getValue(aControlId, aControlAction);
    else
        return uno::Any();
}


// enables a custom template element


void SAL_CALL CWinFileOpenImpl::enableControl(sal_Int16 ControlID, sal_Bool bEnable)
    throw(uno::RuntimeException)
{
    OSL_ASSERT(m_FilePickerState);
    if ( !filterControlCommand( ControlID ))
        m_FilePickerState->enableControl(ControlID, bEnable);
}


void SAL_CALL CWinFileOpenImpl::setLabel( sal_Int16 aControlId, const OUString& aLabel )
    throw (uno::RuntimeException)
{
    OSL_ASSERT(m_FilePickerState);
    if ( !filterControlCommand( aControlId ))
        m_FilePickerState->setLabel(aControlId, aLabel);
}


OUString SAL_CALL CWinFileOpenImpl::getLabel( sal_Int16 aControlId )
        throw (uno::RuntimeException)
{
    OSL_ASSERT(m_FilePickerState);
    if ( !filterControlCommand( aControlId ))
        return m_FilePickerState->getLabel(aControlId);
    else
        return OUString();
}


uno::Sequence<sal_Int16> SAL_CALL CWinFileOpenImpl::getSupportedImageFormats()
    throw (uno::RuntimeException)
{
    return m_Preview->getSupportedImageFormats();
}


sal_Int32 SAL_CALL CWinFileOpenImpl::getTargetColorDepth()
    throw (uno::RuntimeException)
{
    return m_Preview->getTargetColorDepth();
}


sal_Int32 SAL_CALL CWinFileOpenImpl::getAvailableWidth()
        throw (uno::RuntimeException)
{
    return m_Preview->getAvailableWidth();
}


sal_Int32 SAL_CALL CWinFileOpenImpl::getAvailableHeight()
    throw (uno::RuntimeException)
{
    return m_Preview->getAvailableHeight();
}


void SAL_CALL CWinFileOpenImpl::setImage(sal_Int16 aImageFormat, const uno::Any& aImage)
    throw (IllegalArgumentException, uno::RuntimeException)
{
    m_Preview->setImage(aImageFormat,aImage);
}


sal_Bool SAL_CALL CWinFileOpenImpl::setShowState(sal_Bool bShowState)
        throw (uno::RuntimeException)
{
    return m_Preview->setShowState(bShowState);
}


sal_Bool SAL_CALL CWinFileOpenImpl::getShowState()
    throw (uno::RuntimeException)
{
    return m_Preview->getShowState();
}


void SAL_CALL CWinFileOpenImpl::cancel()
{
    if (IsWindow(m_hwndFileOpenDlg))
    {
        // simulate a mouse click to the
        // cancel button
        BOOL const ret = PostMessage(
            m_hwndFileOpenDlg,
            WM_COMMAND,
            MAKEWPARAM(IDCANCEL,BN_CLICKED),
            (LPARAM)GetDlgItem(m_hwndFileOpenDlg, IDCANCEL));
        SAL_WARN_IF(0 == ret, "fpicker", "ERROR: PostMessage() failed!");
    }
}


// returns the id of a custom template element


sal_Int16 SAL_CALL CWinFileOpenImpl::getFocused()
{
    int nID = GetDlgCtrlID(GetFocus());

    // we don't forward id's of standard file open
    // dialog elements (ctlFirst is defined in dlgs.h
    // in MS Platform SDK)
    if (nID >= ctlFirst)
        nID = 0;

    return sal::static_int_cast< sal_Int16 >(nID);
}


inline sal_Bool SAL_CALL CWinFileOpenImpl::IsCustomControlHelpRequested(LPHELPINFO lphi) const
{
    return ((lphi->iCtrlId != IDOK) && (lphi->iCtrlId != IDCANCEL) && (lphi->iCtrlId < ctlFirst));
}


// our own DlgProc because we do subclass the dialog
// we catch the WM_NCDESTROY message in order to erase an entry in our static map
// if one instance dies


LRESULT CALLBACK CWinFileOpenImpl::SubClassFunc(
    HWND hWnd, UINT wMessage, WPARAM wParam, LPARAM lParam)
{
    unsigned int lResult = 0;

    CWinFileOpenImpl* pImpl = dynamic_cast<CWinFileOpenImpl*>(getCurrentInstance(hWnd));

    switch(wMessage)
    {
    case WM_HELP:
    {
        LPHELPINFO lphi = reinterpret_cast<LPHELPINFO>(lParam);

        if (pImpl->IsCustomControlHelpRequested(lphi))
            pImpl->onCustomControlHelpRequest(lphi);
        else
            lResult = CallWindowProc(
                reinterpret_cast<WNDPROC>(pImpl->m_pfnOldDlgProc),
                hWnd,wMessage,wParam,lParam);
    }
    break;

    case WM_SIZE:
        lResult = CallWindowProc(
            reinterpret_cast<WNDPROC>(pImpl->m_pfnOldDlgProc),
            hWnd,wMessage,wParam,lParam);

        pImpl->onWMSize();
        break;

    case WM_WINDOWPOSCHANGED:
        lResult = CallWindowProc(
            reinterpret_cast<WNDPROC>(pImpl->m_pfnOldDlgProc),
            hWnd,wMessage,wParam,lParam);

        pImpl->onWMWindowPosChanged();
        break;

    case WM_SHOWWINDOW:
        lResult = CallWindowProc(
            reinterpret_cast<WNDPROC>(pImpl->m_pfnOldDlgProc),
            hWnd,wMessage,wParam,lParam);

        pImpl->onWMShow((sal_Bool)wParam);
        break;

    case WM_NCDESTROY:
        // restore the old window proc
        SetWindowLongPtr(hWnd, GWLP_WNDPROC,
            reinterpret_cast<LONG_PTR>(pImpl->m_pfnOldDlgProc));

        lResult = CallWindowProc(
            reinterpret_cast<WNDPROC>(pImpl->m_pfnOldDlgProc),
            hWnd,wMessage,wParam,lParam);
        break;

    default:
        lResult = CallWindowProc(
            reinterpret_cast<WNDPROC>(pImpl->m_pfnOldDlgProc),
            hWnd,wMessage,wParam,lParam);
    break;

    } // switch

    return lResult;
}


void SAL_CALL CWinFileOpenImpl::InitControlLabel(HWND hWnd)
{

    // set the labels for all extended controls


    sal_Int16 aCtrlId = sal::static_int_cast< sal_Int16 >(GetDlgCtrlID(hWnd));
    OUString aLabel = m_ResProvider.getResString(aCtrlId);
    if (aLabel.getLength())
        setLabel(aCtrlId, aLabel);
}


// There may be problems with the layout of our custom controls,
// so that they are not aligned with the standard controls of the
// FileOpen dialog.
// We use a simple algorithm to move the custom controls to their
// proper position and resize them.
// Our approach is to align all static text controls with the
// static text control "File name" of the FileOpen dialog,
// all checkboxes and all list/comboboxes will be left aligned with
// the standard combobox edt1/cmb13 (defined in MS platform sdk dlgs.h)
// and all push buttons will be left aligned with the standard
// "OK" button


void SAL_CALL CWinFileOpenImpl::InitCustomControlContainer(HWND hCustomControl)
{
    m_CustomControls->AddControl(
        CCustomControlFactory::CreateCustomControl(hCustomControl,m_hwndFileOpenDlg));
}


void SAL_CALL CWinFileOpenImpl::CacheControlState(HWND hWnd)
{
    OSL_ASSERT(m_FilePickerState && m_NonExecuteFilePickerState);
    m_ExecuteFilePickerState->cacheControlState(hWnd, m_NonExecuteFilePickerState);
}


BOOL CALLBACK CWinFileOpenImpl::EnumChildWndProc(HWND hWnd, LPARAM lParam)
{
    EnumParam* enumParam    = (EnumParam*)lParam;
    CWinFileOpenImpl* pImpl = enumParam->m_instance;

    OSL_ASSERT(pImpl);

    sal_Bool bRet = sal_True;

    switch(enumParam->m_action)
    {
    case INIT_CUSTOM_CONTROLS:
        pImpl->InitControlLabel(hWnd);
        pImpl->InitCustomControlContainer(hWnd);
        break;

    case CACHE_CONTROL_VALUES:
        pImpl->CacheControlState(hWnd);
    break;

    default:
        // should not end here
        OSL_ASSERT(sal_False);
    }

    return bRet;
}


sal_uInt32 SAL_CALL CWinFileOpenImpl::onFileOk()
{
    m_NonExecuteFilePickerState->reset();

    EnumParam enumParam(CACHE_CONTROL_VALUES,this);

    EnumChildWindows(
        m_hwndFileOpenDlgChild,
        CWinFileOpenImpl::EnumChildWndProc,
        (LPARAM)&enumParam);

    return 0;
}


void SAL_CALL CWinFileOpenImpl::onSelChanged(HWND)
{
    // the windows file open dialog sends an initial
    // SelChanged message after the InitDone message
    // when the dialog is about to be opened
    // if the lpstrFile buffer of the OPENFILENAME is
    // empty (zero length string) the windows file open
    // dialog sends a WM_SETTEXT message with an empty
    // string to the file name edit line
    // this would overwritte our text when we would set
    // the default name in onInitDone, so we have to
    // remember that this is the first SelChanged message
    // and set the default name here to overwrite the
    // windows setting
    InitialSetDefaultName();

    FilePickerEvent evt;
    m_FilePicker->fileSelectionChanged(evt);
}

// #i40865# The size of the standard labels 'File name'
// and 'File type' is to short in some cases when the
// label will be changed (e.g. in the Brazil version).
// We just make sure that the labels are using the maximum
// available space.
void CWinFileOpenImpl::EnlargeStdControlLabels() const
{
    HWND hFilterBoxLabel = GetDlgItem(m_hwndFileOpenDlg, stc2);
    HWND hFileNameBoxLabel = GetDlgItem(m_hwndFileOpenDlg, stc3);
    HWND hFileNameBox = GetDlgItem(m_hwndFileOpenDlg, cmb13);
    if (!hFileNameBox)
        hFileNameBox = GetDlgItem(m_hwndFileOpenDlg, edt1); // since Win2k it is cmb13 or edt1

    HWND hFilterBox = GetDlgItem(m_hwndFileOpenDlg, cmb1);
    HWND hOkButton = GetDlgItem(m_hwndFileOpenDlg, IDOK);

    // Move filter and file name box nearer to OK and Cancel button
    RECT rcOkButton;
    GetWindowRect(hOkButton, &rcOkButton);

    const int MAX_GAP = 10;
    const int OFFSET = 0;

    RECT rcFileNameBox;
    GetWindowRect(hFileNameBox, &rcFileNameBox);
    int w = rcFileNameBox.right - rcFileNameBox.left;
    int h = rcFileNameBox.bottom - rcFileNameBox.top;

    int gap = rcOkButton.left - rcFileNameBox.right;
    gap = (gap > MAX_GAP) ? gap - MAX_GAP : gap;

    ScreenToClient(m_hwndFileOpenDlg, (LPPOINT)&rcFileNameBox);
    MoveWindow(hFileNameBox, rcFileNameBox.left + gap + OFFSET, rcFileNameBox.top, w - OFFSET, h, true);

    RECT rcFilterBox;
    GetWindowRect(hFilterBox, &rcFilterBox);
    w = rcFilterBox.right - rcFilterBox.left;
    h = rcFilterBox.bottom - rcFilterBox.top;
    ScreenToClient(m_hwndFileOpenDlg, (LPPOINT)&rcFilterBox);
    MoveWindow(hFilterBox, rcFilterBox.left + gap + OFFSET, rcFilterBox.top, w - OFFSET, h, true);

    // get the new window rect
    GetWindowRect(hFileNameBox, &rcFileNameBox);

    RECT rcFilterBoxLabel;
    GetWindowRect(hFilterBoxLabel, &rcFilterBoxLabel);
    int offset = rcFileNameBox.left - rcFilterBoxLabel.right - 1;

    w = rcFilterBoxLabel.right - rcFilterBoxLabel.left + offset;
    h = rcFilterBoxLabel.bottom - rcFilterBoxLabel.top;
    ScreenToClient(m_hwndFileOpenDlg, (LPPOINT)&rcFilterBoxLabel);
    MoveWindow(hFilterBoxLabel, rcFilterBoxLabel.left, rcFilterBoxLabel.top, w, h, true);

    RECT rcFileNameBoxLabel;
    GetWindowRect(hFileNameBoxLabel, &rcFileNameBoxLabel);
    w = rcFileNameBoxLabel.right - rcFileNameBoxLabel.left + offset;
    h = rcFileNameBoxLabel.bottom - rcFileNameBoxLabel.top;
    ScreenToClient(m_hwndFileOpenDlg, (LPPOINT)&rcFileNameBoxLabel);
    MoveWindow(hFileNameBoxLabel, rcFileNameBoxLabel.left, rcFileNameBoxLabel.top, w, h, true);
}

void SAL_CALL CWinFileOpenImpl::onInitDone()
{
    m_Preview->setParent(m_hwndFileOpenDlg);

    // but now we have a valid parent handle
    m_HelpPopupWindow.setParent(m_hwndFileOpenDlg);

    EnlargeStdControlLabels();

    // #99826
    // Set the online filepicker state before initializing
    // the control labels from the resource else we are
    // overriding the offline settings
    m_ExecuteFilePickerState->setHwnd(m_hwndFileOpenDlgChild);

    m_FilePickerState = m_ExecuteFilePickerState;

    // initialize controls from cache

    EnumParam enumParam(INIT_CUSTOM_CONTROLS,this);

    EnumChildWindows(
        m_hwndFileOpenDlgChild,
        CWinFileOpenImpl::EnumChildWndProc,
        (LPARAM)&enumParam);

    m_ExecuteFilePickerState->initFilePickerControls(
        m_NonExecuteFilePickerState->getControlCommand());

    SetDefaultExtension();

    m_CustomControls->Align();

    m_CustomControls->SetFont(
        reinterpret_cast<HFONT>(SendMessageW(m_hwndFileOpenDlg, WM_GETFONT, 0, 0)));

    // resume event notification that was
    // defered in onInitDialog
    m_FilePicker->resumeEventNotification();

    //#105996 let vcl know that now a system window is active
    BOOL const ret = PostMessage(
        HWND_BROADCAST,
        RegisterWindowMessageW(L"SYSTEM_WINDOW_ACTIVATED"),
        0,
        0);
    SAL_WARN_IF(0 == ret, "fpicker", "ERROR: PostMessage() failed!");

    // call the parent function to center the
    // dialog to its parent
    CFileOpenDialog::onInitDone();
}


void SAL_CALL CWinFileOpenImpl::onFolderChanged()
{
    FilePickerEvent evt;
    m_FilePicker->directoryChanged(evt);
}


void SAL_CALL CWinFileOpenImpl::onTypeChanged(sal_uInt32)
{
    SetDefaultExtension();

    FilePickerEvent evt;
    evt.ElementId = LISTBOX_FILTER;
    m_FilePicker->controlStateChanged(evt);
}


// onMessageCommand handler


sal_uInt32 SAL_CALL CWinFileOpenImpl::onCtrlCommand(
    HWND, sal_uInt16 ctrlId, sal_uInt16)
{
    SetDefaultExtension();

    if (ctrlId < ctlFirst)
    {
        FilePickerEvent evt;
        evt.ElementId = ctrlId;
        m_FilePicker->controlStateChanged(evt);
    }

    return 0;
}


void CWinFileOpenImpl::onWMSize()
{
    m_Preview->notifyParentSizeChanged();
    m_CustomControls->Align();
    m_FilePicker->dialogSizeChanged();
}


void CWinFileOpenImpl::onWMShow(sal_Bool bShow)
{
    m_Preview->notifyParentShow(bShow);
}


void CWinFileOpenImpl::onWMWindowPosChanged()
{
    m_Preview->notifyParentWindowPosChanged();
}


void CWinFileOpenImpl::onCustomControlHelpRequest(LPHELPINFO lphi)
{
    FilePickerEvent evt;
    evt.ElementId = sal::static_int_cast< sal_Int16 >(lphi->iCtrlId);

    OUString aPopupHelpText = m_FilePicker->helpRequested(evt);

    if (aPopupHelpText.getLength())
    {
        m_HelpPopupWindow.setText(aPopupHelpText);

        DWORD dwMsgPos = GetMessagePos();
        m_HelpPopupWindow.show(LOWORD(dwMsgPos),HIWORD(dwMsgPos));
    }
}


void SAL_CALL CWinFileOpenImpl::onInitDialog(HWND hwndDlg)
{
    // subclass the dialog window
    m_pfnOldDlgProc =
        reinterpret_cast<WNDPROC>(
            SetWindowLongPtr( hwndDlg, GWLP_WNDPROC,
            reinterpret_cast<LONG_PTR>(SubClassFunc)));
}


// processing before showing the dialog


bool SAL_CALL CWinFileOpenImpl::preModal()
{
    CFileOpenDialog::setFilter(
        makeWinFilterBuffer(*m_filterContainer.get()));

    return true;
}


// processing after showing the dialog


void CWinFileOpenImpl::postModal(sal_Int16 nDialogResult)
{
    CFileOpenDialog::postModal(nDialogResult);

    // empty the container in order to get rid off
    // invalid controls in case someone calls execute
    // twice in sequence with the same instance
    m_CustomControls->RemoveAllControls();

    m_FilePickerState = m_NonExecuteFilePickerState;
}


void SAL_CALL CWinFileOpenImpl::SetDefaultExtension()
{
    HWND hwndChkSaveWithExt = GetDlgItem(m_hwndFileOpenDlgChild, 100);

    if (hwndChkSaveWithExt)
    {
        uno::Any aAny = CheckboxGetState(hwndChkSaveWithExt);
        sal_Bool bChecked = *reinterpret_cast<const sal_Bool*>(aAny.getValue());

        if (bChecked)
        {
            sal_uInt32 nIndex = getSelectedFilterIndex();

            OUString currentFilter;
            if (nIndex > 0)
            {
                // filter index of the base class starts with 1
                m_filterContainer->getFilter(nIndex - 1, currentFilter);

                if (currentFilter.getLength())
                {
                    OUString FilterExt;
                    m_filterContainer->getFilter(currentFilter, FilterExt);

                    sal_Int32 posOfPoint = FilterExt.indexOf(L'.');
                    const sal_Unicode* pFirstExtStart = FilterExt.getStr() + posOfPoint + 1;

                    sal_Int32 posOfSemiColon = FilterExt.indexOf(L';') - 1;
                    if (posOfSemiColon < 0)
                        posOfSemiColon = FilterExt.getLength() - 1;

                    FilterExt = OUString(pFirstExtStart, posOfSemiColon - posOfPoint);

                    SendMessageW(m_hwndFileOpenDlg, CDM_SETDEFEXT, 0, reinterpret_cast<LPARAM>(FilterExt.getStr()));
                 }
            }
        }
        else
        {
            SendMessageW(m_hwndFileOpenDlg, CDM_SETDEFEXT, 0, reinterpret_cast<LPARAM>(L""));
        }
    }

    // !!! HACK !!!
}


void SAL_CALL CWinFileOpenImpl::InitialSetDefaultName()
{
    // manually setting the file name that appears
    // initially in the file-name-box of the file
    // open dialog (reason: see above setDefaultName)
    if (m_bInitialSelChanged && m_defaultName.getLength())
    {
        // under W2k by default there is a combobox instead
        // of an edit field for the file name edit field
        // the control id of this box is cmb13 and not
        // edt1 as before.
        // However, edt1 is still possible. See fdo#74295
        HWND hFileNameBox = GetDlgItem(m_hwndFileOpenDlg, cmb13);
        if (!hFileNameBox)
            hFileNameBox = GetDlgItem(m_hwndFileOpenDlg, edt1);
        SetWindowTextW(hFileNameBox, reinterpret_cast<PCWSTR>(m_defaultName.getStr()));
    }

    m_bInitialSelChanged = sal_False;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */