Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FileAssoc.cpp « mpc-hc « src - github.com/mpc-hc/mpc-hc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 032d7318a40f90227bb401f02bd0561d42448af4 (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
/*
 * (C) 2003-2006 Gabest
 * (C) 2006-2014, 2016-2017 see Authors.txt
 *
 * This file is part of MPC-HC.
 *
 * MPC-HC is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * MPC-HC 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "stdafx.h"
#include <VersionHelpersInternal.h>
#include "mplayerc.h"
#include "FileAssoc.h"
#include "resource.h"
#include "PathUtils.h"


// TODO: change this along with the root key for settings and the mutex name to
//       avoid possible risks of conflict with the old MPC (non HC version).
#ifdef _WIN64
#define PROGID _T("mplayerc64")
#else
#define PROGID _T("mplayerc")
#endif // _WIN64

CFileAssoc::IconLib::IconLib(GetIconIndexFunc fnGetIconIndex, GetIconLibVersionFunc fnGetIconLibVersion, HMODULE hLib)
    : m_fnGetIconIndex(fnGetIconIndex)
    , m_fnGetIconLibVersion(fnGetIconLibVersion)
    , m_hLib(hLib)
{
    ASSERT(fnGetIconIndex && fnGetIconLibVersion && hLib);
}

CFileAssoc::IconLib::~IconLib()
{
    VERIFY(FreeLibrary(m_hLib));
}

int CFileAssoc::IconLib::GetIconIndex(const CString& str) const
{
    return m_fnGetIconIndex(str);
}

UINT CFileAssoc::IconLib::GetVersion() const
{
    return m_fnGetIconLibVersion();
}

void CFileAssoc::IconLib::SaveVersion() const
{
    AfxGetApp()->WriteProfileInt(IDS_R_SETTINGS, IDS_RS_ICON_LIB_VERSION, m_fnGetIconLibVersion());
}

CFileAssoc::CFileAssoc()
    : m_iconLibPath(PathUtils::CombinePaths(PathUtils::GetProgramPath(), _T("mpciconlib.dll")))
    , m_strRegisteredAppName(_T("Media Player Classic"))
    , m_strOldAssocKey(_T("PreviousRegistration"))
    , m_strRegisteredAppKey(_T("Software\\Clients\\Media\\Media Player Classic\\Capabilities"))
    , m_strRegAppFileAssocKey(_T("Software\\Clients\\Media\\Media Player Classic\\Capabilities\\FileAssociations"))
    , m_strOpenCommand(_T("\"") + PathUtils::GetProgramPath(true) + _T("\" \"%1\""))
    , m_strEnqueueCommand(_T("\"") + PathUtils::GetProgramPath(true) + _T("\" /add \"%1\""))
    , m_bNoRecentDocs(false)
    , m_checkIconsAssocInactiveEvent(TRUE, TRUE) // initially set, manual reset
{
    // Default manager (requires at least Vista)
    VERIFY(CoCreateInstance(CLSID_ApplicationAssociationRegistration, nullptr,
                            CLSCTX_INPROC, IID_PPV_ARGS(&m_pAAR)) != CO_E_NOTINITIALIZED);

    m_handlers[0] = { _T("VideoFiles"), _T(" %1"), IDS_AUTOPLAY_PLAYVIDEO };
    m_handlers[1] = { _T("MusicFiles"), _T(" %1"), IDS_AUTOPLAY_PLAYMUSIC };
    m_handlers[2] = { _T("CDAudio"), _T(" %1 /cd"), IDS_AUTOPLAY_PLAYAUDIOCD };
    m_handlers[3] = { _T("DVDMovie"), _T(" %1 /dvd"), IDS_AUTOPLAY_PLAYDVDMOVIE };
}

CFileAssoc::~CFileAssoc()
{
    HANDLE hEvent = m_checkIconsAssocInactiveEvent;
    DWORD dwEvent;
    VERIFY(CoWaitForMultipleHandles(0, INFINITE, 1, &hEvent, &dwEvent) == S_OK);
}

std::shared_ptr<const CFileAssoc::IconLib> CFileAssoc::GetIconLib() const
{
    std::shared_ptr<IconLib> ret;
    if (HMODULE hLib = LoadLibrary(m_iconLibPath)) {
        auto fnGetIconIndex = reinterpret_cast<IconLib::GetIconIndexFunc>(GetProcAddress(hLib, "GetIconIndex"));
        auto fnGetIconLibVersion = reinterpret_cast<IconLib::GetIconLibVersionFunc>(GetProcAddress(hLib, "GetIconLibVersion"));
        if (fnGetIconIndex && fnGetIconLibVersion) {
            ret = std::make_shared<IconLib>(fnGetIconIndex, fnGetIconLibVersion, hLib);
        } else {
            VERIFY(FreeLibrary(hLib));
        }
    }
    return ret;
}

void CFileAssoc::SetNoRecentDocs(bool bNoRecentDocs, bool bUpdateAssocs /*= false*/)
{
    if (bNoRecentDocs == m_bNoRecentDocs) {
        bUpdateAssocs = false;
    } else {
        m_bNoRecentDocs = bNoRecentDocs;
    }

    CAtlList<CString> exts;
    if (bUpdateAssocs && GetAssociatedExtensionsFromRegistry(exts)) {
        CRegKey key;
        POSITION pos = exts.GetHeadPosition();
        while (pos) {
            const CString& ext = exts.GetNext(pos);

            if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, PROGID + ext)) {
                if (m_bNoRecentDocs) {
                    key.SetStringValue(_T("NoRecentDocs"), _T(""));
                } else {
                    key.DeleteValue(_T("NoRecentDocs"));
                }
            }
        }
    }
}

bool CFileAssoc::RegisterApp()
{
    bool success = false;

    if (m_pAAR) {
        CString appIcon = _T("\"") + PathUtils::GetProgramPath(true) + _T("\",0");

        // Register MPC-HC for the windows "Default application" manager
        CRegKey key;

        if (ERROR_SUCCESS == key.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\RegisteredApplications"))) {
            key.SetStringValue(_T("Media Player Classic"), m_strRegisteredAppKey);

            if (ERROR_SUCCESS == key.Create(HKEY_LOCAL_MACHINE, m_strRegisteredAppKey)) {
                // ==>>  TODO icon !!!
                key.SetStringValue(_T("ApplicationDescription"), ResStr(IDS_APP_DESCRIPTION), REG_EXPAND_SZ);
                key.SetStringValue(_T("ApplicationIcon"), appIcon, REG_EXPAND_SZ);
                key.SetStringValue(_T("ApplicationName"), ResStr(IDR_MAINFRAME), REG_EXPAND_SZ);

                success = true;
            }
        }
    }

    return success;
}

bool CFileAssoc::Register(CString ext, CString strLabel, bool bRegister, bool bRegisterContextMenuEntries, bool bAssociatedWithIcon)
{
    CRegKey key;
    CString strProgID = PROGID + ext;

    if (!bRegister) {
        // On Windows 8, an app can't set itself as the default handler for a format
        if (!IsWindows8OrGreater() && bRegister != IsRegistered(ext)) {
            SetFileAssociation(ext, strProgID, bRegister);
        }

        key.Attach(HKEY_CLASSES_ROOT);
        key.RecurseDeleteKey(strProgID);

        if (ERROR_SUCCESS == key.Open(HKEY_LOCAL_MACHINE, m_strRegAppFileAssocKey)) {
            key.DeleteValue(ext);
        }

        return true;
    } else {
        // Create ProgID for this file type
        if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID)
                || ERROR_SUCCESS != key.SetStringValue(nullptr, strLabel)) {
            return false;
        }

        if (m_bNoRecentDocs) {
            key.SetStringValue(_T("NoRecentDocs"), _T(""));
        } else {
            key.DeleteValue(_T("NoRecentDocs"));
        }

        CString appIcon = _T("\"") + PathUtils::GetProgramPath(true) + _T("\",0");

        // Add to playlist option
        if (bRegisterContextMenuEntries) {
            if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\shell\\enqueue"))
                    || ERROR_SUCCESS != key.SetStringValue(nullptr, ResStr(IDS_ADD_TO_PLAYLIST))
                    || ERROR_SUCCESS != key.SetStringValue(_T("Icon"), appIcon)
                    || ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\shell\\enqueue\\command"))
                    || ERROR_SUCCESS != key.SetStringValue(nullptr, m_strEnqueueCommand)) {
                return false;
            }
        } else {
            key.Close();
            key.Attach(HKEY_CLASSES_ROOT);
            key.RecurseDeleteKey(strProgID + _T("\\shell\\enqueue"));
        }

        // Play option
        if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\shell\\open"))) {
            return false;
        }
        if (bRegisterContextMenuEntries) {
            if (ERROR_SUCCESS != key.SetStringValue(nullptr, ResStr(IDS_OPEN_WITH_MPC))
                    || ERROR_SUCCESS != key.SetStringValue(_T("Icon"), appIcon)) {
                return false;
            }
        } else {
            if (ERROR_SUCCESS != key.SetStringValue(nullptr, _T(""))
                    || ERROR_SUCCESS != key.SetStringValue(_T("Icon"), _T(""))) {
                return false;
            }
        }

        if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\shell\\open\\command"))
                || ERROR_SUCCESS != key.SetStringValue(nullptr, m_strOpenCommand)) {
            return false;
        }

        if (ERROR_SUCCESS != key.Create(HKEY_LOCAL_MACHINE, m_strRegAppFileAssocKey)
                || key.SetStringValue(ext, strProgID)) {
            return false;
        }

        if (bAssociatedWithIcon) {
            if (auto iconLib = GetIconLib()) {
                int iconIndex = iconLib->GetIconIndex(ext);

                /* icon_index value -1 means no icon was found in the iconlib for the file extension */
                if (iconIndex >= 0 && ExtractIcon(AfxGetApp()->m_hInstance, m_iconLibPath, iconIndex)) {
                    appIcon.Format(_T("\"%s\",%d"), m_iconLibPath, iconIndex);
                }
            }

            if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\DefaultIcon"))
                    || ERROR_SUCCESS != key.SetStringValue(nullptr, appIcon)) {
                return false;
            }
        } else {
            key.Close();
            key.Attach(HKEY_CLASSES_ROOT);
            key.RecurseDeleteKey(strProgID + _T("\\DefaultIcon"));
        }

        // On Windows 8, an app can't set itself as the default handler for a format
        if (!IsWindows8OrGreater() && bRegister != IsRegistered(ext)) {
            SetFileAssociation(ext, strProgID, bRegister);
        }

        return true;
    }
}

bool CFileAssoc::SetFileAssociation(CString strExt, CString strProgID, bool bRegister)
{
    CString extOldReg/*, extOldIcon*/;
    CRegKey key;
    HRESULT hr = S_OK;
    TCHAR   buff[MAX_PATH];
    ULONG   len = _countof(buff);
    ZeroMemory(buff, sizeof(buff));

    if (m_pAAR) {
        // The Vista/Seven way
        CString strNewApp;
        if (bRegister) {
            // Create non existing file type
            if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strExt)) {
                return false;
            }

            CComHeapPtr<WCHAR> pszCurrentAssociation;
            // Save the application currently associated
            if (SUCCEEDED(m_pAAR->QueryCurrentDefault(strExt, AT_FILEEXTENSION, AL_EFFECTIVE, &pszCurrentAssociation))) {
                if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID)) {
                    return false;
                }

                key.SetStringValue(m_strOldAssocKey, pszCurrentAssociation);

                /*
                // Get current icon for file type
                if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, CString(pszCurrentAssociation) + _T("\\DefaultIcon")))
                {
                    len = sizeof(buff);
                    ZeroMemory(buff, sizeof(buff));
                    if (ERROR_SUCCESS == key.QueryStringValue(nullptr, buff, &len) && !CString(buff).Trim().IsEmpty())
                    {
                        if (ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\DefaultIcon")))
                            key.SetStringValue (nullptr, buff);
                    }
                }
                */
            }
            strNewApp = m_strRegisteredAppName;
        } else {
            if (ERROR_SUCCESS != key.Open(HKEY_CLASSES_ROOT, strProgID)) {
                return false;
            }

            if (ERROR_SUCCESS == key.QueryStringValue(m_strOldAssocKey, buff, &len)) {
                strNewApp = buff;
            }

            // TODO : retrieve registered app name from previous association (or find Bill function for that...)
        }

        hr = m_pAAR->SetAppAsDefault(strNewApp, strExt, AT_FILEEXTENSION);
    } else {
        // The XP way
        if (bRegister) {
            // Set new association
            if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strExt)) {
                return false;
            }

            len = _countof(buff);
            ZeroMemory(buff, sizeof(buff));
            if (ERROR_SUCCESS == key.QueryStringValue(nullptr, buff, &len) && !CString(buff).Trim().IsEmpty()) {
                extOldReg = buff;
            }
            if (ERROR_SUCCESS != key.SetStringValue(nullptr, strProgID)) {
                return false;
            }

            /*
            // Get current icon for file type
            if (!extOldReg.IsEmpty())
            {
                if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, extoldreg + _T("\\DefaultIcon")))
                {
                    len = sizeof(buff);
                    ZeroMemory(buff, sizeof(buff));
                    if (ERROR_SUCCESS == key.QueryStringValue(nullptr, buff, &len) && !CString(buff).Trim().IsEmpty())
                        extOldIcon = buff;
                }
            }
            */

            // Save old association
            if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID)) {
                return false;
            }
            key.SetStringValue(m_strOldAssocKey, extOldReg);

            /*
            if (!extOldIcon.IsEmpty() && (ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\DefaultIcon"))))
                key.SetStringValue(nullptr, extOldIcon);
            */
        } else {
            // Get previous association
            len = _countof(buff);
            ZeroMemory(buff, sizeof(buff));
            if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID)) {
                return false;
            }
            if (ERROR_SUCCESS == key.QueryStringValue(m_strOldAssocKey, buff, &len) && !CString(buff).Trim().IsEmpty()) {
                extOldReg = buff;
            }

            // Set previous association
            if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strExt)) {
                return false;
            }
            key.SetStringValue(nullptr, extOldReg);
        }
    }

    return SUCCEEDED(hr);
}

bool CFileAssoc::IsRegistered(CString ext) const
{
    BOOL bIsDefault = FALSE;
    CString strProgID = PROGID + ext;

    if (IsWindows8OrGreater()) {
        // The Eight way
        bIsDefault = TRUE; // Check only if MPC-HC is registered as able to handle that format, not if it's the default.
    } else if (m_pAAR) {
        // The Vista/Seven way
        m_pAAR->QueryAppIsDefault(ext, AT_FILEEXTENSION, AL_EFFECTIVE, m_strRegisteredAppName, &bIsDefault);
    } else {
        // The XP way
        CRegKey key;
        TCHAR   buff[MAX_PATH];
        ULONG   len = _countof(buff);
        ZeroMemory(buff, sizeof(buff));

        if (ERROR_SUCCESS != key.Open(HKEY_CLASSES_ROOT, ext, KEY_READ)
                || ERROR_SUCCESS != key.QueryStringValue(nullptr, buff, &len)
                || CString(buff).Trim().IsEmpty()) {
            return false;
        }

        bIsDefault = (buff == strProgID);
    }

    // Check if association is for this instance of MPC-HC
    if (bIsDefault) {
        CRegKey key;
        TCHAR   buff[MAX_PATH];
        ULONG   len = _countof(buff);

        bIsDefault = FALSE;
        if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, strProgID + _T("\\shell\\open\\command"), KEY_READ)) {
            if (ERROR_SUCCESS == key.QueryStringValue(nullptr, buff, &len)) {
                bIsDefault = (m_strOpenCommand.CompareNoCase(CString(buff)) == 0);
            }
        }
    }

    return !!bIsDefault;
}

bool CFileAssoc::AreRegisteredFileContextMenuEntries(CString strExt) const
{
    CRegKey key;
    TCHAR   buff[MAX_PATH];
    ULONG   len = _countof(buff);
    CString strProgID = PROGID + strExt;
    bool    registered = false;

    if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, strProgID + _T("\\shell\\open"), KEY_READ)) {
        CString strCommand(StrRes(IDS_OPEN_WITH_MPC));
        if (ERROR_SUCCESS == key.QueryStringValue(nullptr, buff, &len)) {
            registered = (strCommand.CompareNoCase(CString(buff)) == 0);
        }
    }

    return registered;
}

bool CFileAssoc::Register(const CMediaFormatCategory& mfc, bool bRegister, bool bRegisterContextMenuEntries, bool bAssociatedWithIcon)
{
    if (!mfc.IsAssociable()) {
        ASSERT(FALSE);
        return false;
    }

    CAtlList<CString> exts;
    ExplodeMin(mfc.GetExtsWithPeriod(), exts, ' ');

    CString strLabel = mfc.GetDescription();
    bool res = true;

    POSITION pos = exts.GetHeadPosition();
    while (pos) {
        res &= Register(exts.GetNext(pos), strLabel, bRegister, bRegisterContextMenuEntries, bAssociatedWithIcon);
    }

    return res;
}

CFileAssoc::reg_state_t CFileAssoc::IsRegistered(const CMediaFormatCategory& mfc) const
{
    CAtlList<CString> exts;
    ExplodeMin(mfc.GetExtsWithPeriod(), exts, ' ');

    size_t cnt = 0;

    POSITION pos = exts.GetHeadPosition();
    while (pos) {
        if (CFileAssoc::IsRegistered(exts.GetNext(pos))) {
            cnt++;
        }
    }

    reg_state_t res;
    if (cnt == 0) {
        res = NOT_REGISTERED;
    } else if (cnt == exts.GetCount()) {
        res = ALL_REGISTERED;
    } else {
        res = SOME_REGISTERED;
    }

    return res;
}

CFileAssoc::reg_state_t CFileAssoc::AreRegisteredFileContextMenuEntries(const CMediaFormatCategory& mfc) const
{
    CAtlList<CString> exts;
    ExplodeMin(mfc.GetExtsWithPeriod(), exts, ' ');

    size_t cnt = 0;

    POSITION pos = exts.GetHeadPosition();
    while (pos) {
        if (CFileAssoc::AreRegisteredFileContextMenuEntries(exts.GetNext(pos))) {
            cnt++;
        }
    }

    reg_state_t res;
    if (cnt == 0) {
        res = NOT_REGISTERED;
    } else if (cnt == exts.GetCount()) {
        res = ALL_REGISTERED;
    } else {
        res = SOME_REGISTERED;
    }

    return res;
}

bool CFileAssoc::RegisterFolderContextMenuEntries(bool bRegister)
{
    CRegKey key;
    bool success;

    if (bRegister) {
        success = false;

        CString appIcon = _T("\"") + PathUtils::GetProgramPath(true) + _T("\",0");

        if (ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, _T("Directory\\shell\\") PROGID _T(".enqueue"))) {
            key.SetStringValue(nullptr, ResStr(IDS_ADD_TO_PLAYLIST));
            key.SetStringValue(_T("Icon"), appIcon);

            if (ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, _T("Directory\\shell\\") PROGID _T(".enqueue\\command"))) {
                key.SetStringValue(nullptr, m_strEnqueueCommand);
                success = true;
            }
        }

        if (success && ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, _T("Directory\\shell\\") PROGID _T(".play"))) {
            success = false;

            key.SetStringValue(nullptr, ResStr(IDS_OPEN_WITH_MPC));
            key.SetStringValue(_T("Icon"), appIcon);

            if (ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, _T("Directory\\shell\\") PROGID _T(".play\\command"))) {
                key.SetStringValue(nullptr, m_strOpenCommand);
                success = true;
            }
        }

    } else {
        key.Attach(HKEY_CLASSES_ROOT);
        success  = (ERROR_SUCCESS == key.RecurseDeleteKey(_T("Directory\\shell\\") PROGID _T(".enqueue")));
        success &= (ERROR_SUCCESS == key.RecurseDeleteKey(_T("Directory\\shell\\") PROGID _T(".play")));
    }

    return success;
}

bool CFileAssoc::AreRegisteredFolderContextMenuEntries() const
{
    CRegKey key;
    TCHAR   buff[MAX_PATH];
    ULONG   len = _countof(buff);
    bool    registered = false;

    if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, _T("Directory\\shell\\") PROGID _T(".play\\command"), KEY_READ)) {
        if (ERROR_SUCCESS == key.QueryStringValue(nullptr, buff, &len)) {
            registered = (m_strOpenCommand.CompareNoCase(CString(buff)) == 0);
        }
    }

    return registered;
}

bool CFileAssoc::RegisterAutoPlay(autoplay_t ap, bool bRegister)
{
    CString exe = PathUtils::GetProgramPath(true);

    size_t i = (size_t)ap;
    if (i >= m_handlers.size()) {
        return false;
    }

    CRegKey key;

    if (bRegister) {
        if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, _T("MediaPlayerClassic.Autorun"))) {
            return false;
        }
        key.Close();

        if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT,
                                        _T("MediaPlayerClassic.Autorun\\Shell\\Play") + m_handlers[i].verb + _T("\\Command"))) {
            return false;
        }
        key.SetStringValue(nullptr, _T("\"") + exe + _T("\"") + m_handlers[i].cmd);
        key.Close();

        if (ERROR_SUCCESS != key.Create(HKEY_LOCAL_MACHINE,
                                        _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoplayHandlers\\Handlers\\MPCPlay") + m_handlers[i].verb + _T("OnArrival"))) {
            return false;
        }
        key.SetStringValue(_T("Action"), ResStr(m_handlers[i].action));
        key.SetStringValue(_T("Provider"), _T("Media Player Classic"));
        key.SetStringValue(_T("InvokeProgID"), _T("MediaPlayerClassic.Autorun"));
        key.SetStringValue(_T("InvokeVerb"), _T("Play") + m_handlers[i].verb);
        key.SetStringValue(_T("DefaultIcon"), exe + _T(",0"));
        key.Close();

        if (ERROR_SUCCESS != key.Create(HKEY_LOCAL_MACHINE,
                                        _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoplayHandlers\\EventHandlers\\Play") + m_handlers[i].verb + _T("OnArrival"))) {
            return false;
        }
        key.SetStringValue(_T("MPCPlay") + m_handlers[i].verb + _T("OnArrival"), _T(""));
        key.Close();
    } else {
        if (ERROR_SUCCESS != key.Create(HKEY_LOCAL_MACHINE,
                                        _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoplayHandlers\\EventHandlers\\Play") + m_handlers[i].verb + _T("OnArrival"))) {
            return false;
        }
        key.DeleteValue(_T("MPCPlay") + m_handlers[i].verb + _T("OnArrival"));
        key.Close();
    }

    return true;
}

bool CFileAssoc::IsAutoPlayRegistered(autoplay_t ap) const
{
    ULONG len;
    TCHAR buff[MAX_PATH];
    CString exe = PathUtils::GetProgramPath(true);

    size_t i = (size_t)ap;
    if (i >= m_handlers.size()) {
        return false;
    }

    CRegKey key;

    if (ERROR_SUCCESS != key.Open(HKEY_LOCAL_MACHINE,
                                  _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoplayHandlers\\EventHandlers\\Play") + m_handlers[i].verb + _T("OnArrival"),
                                  KEY_READ)) {
        return false;
    }
    len = _countof(buff);
    if (ERROR_SUCCESS != key.QueryStringValue(_T("MPCPlay") + m_handlers[i].verb + _T("OnArrival"), buff, &len)) {
        return false;
    }
    key.Close();

    if (ERROR_SUCCESS != key.Open(HKEY_CLASSES_ROOT,
                                  _T("MediaPlayerClassic.Autorun\\Shell\\Play") + m_handlers[i].verb + _T("\\Command"),
                                  KEY_READ)) {
        return false;
    }
    len = _countof(buff);
    if (ERROR_SUCCESS != key.QueryStringValue(nullptr, buff, &len)) {
        return false;
    }
    if (_tcsnicmp(_T("\"") + exe, buff, exe.GetLength() + 1)) {
        return false;
    }
    key.Close();

    return true;
}

bool CFileAssoc::GetAssociatedExtensions(const CMediaFormats& mf, CAtlList<CString>& exts) const
{
    exts.RemoveAll();

    CAtlList<CString> mfcExts;
    for (size_t i = 0, cnt = mf.GetCount(); i < cnt; i++) {
        ExplodeMin(mf[i].GetExtsWithPeriod(), mfcExts, _T(' '));

        POSITION pos = mfcExts.GetHeadPosition();
        while (pos) {
            const CString ext = mfcExts.GetNext(pos);
            if (IsRegistered(ext)) {
                exts.AddTail(ext);
            }
        }
    }

    return !exts.IsEmpty();
}

bool CFileAssoc::GetAssociatedExtensionsFromRegistry(CAtlList<CString>& exts) const
{
    exts.RemoveAll();

    CRegKey rkHKCR(HKEY_CLASSES_ROOT);
    LONG ret;
    DWORD i = 0;
    CString keyName, ext;
    DWORD len = MAX_PATH;

    while ((ret = rkHKCR.EnumKey(i, keyName.GetBuffer(len), &len)) != ERROR_NO_MORE_ITEMS) {
        if (ret == ERROR_SUCCESS) {
            keyName.ReleaseBuffer(len);

            if (keyName.Find(PROGID) == 0) {
                ext = keyName.Mid(_countof(PROGID) - 1);

                if (IsRegistered(ext)) {
                    exts.AddTail(ext);
                }
            }

            i++;
            len = MAX_PATH;
        }
    }

    return !exts.IsEmpty();
}

bool CFileAssoc::ReAssocIcons(const CAtlList<CString>& exts)
{
    auto iconLib = GetIconLib();
    if (!iconLib) {
        return false;
    }
    iconLib->SaveVersion();

    const CString progPath = PathUtils::GetProgramPath(true);

    CRegKey key;

    POSITION pos = exts.GetHeadPosition();
    while (pos) {
        const CString ext = exts.GetNext(pos);
        const CString strProgID = PROGID + ext;
        CString appIcon;

        int iconIndex = iconLib->GetIconIndex(ext);

        /* icon_index value -1 means no icon was found in the iconlib for the file extension */
        if (iconIndex >= 0 && ExtractIcon(AfxGetApp()->m_hInstance, m_iconLibPath, iconIndex)) {
            appIcon.Format(_T("\"%s\",%d"), m_iconLibPath, iconIndex);
        }

        /* no icon was found for the file extension, so use MPC-HC's icon */
        if (appIcon.IsEmpty()) {
            appIcon = _T("\"") + progPath + _T("\",0");
        }

        if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\DefaultIcon"))
                || ERROR_SUCCESS != key.SetStringValue(nullptr, appIcon)) {
            return false;
        }

        key.Close();
    }

    return true;
}

static HRESULT CALLBACK TaskDialogCallbackProc(HWND hwnd, UINT uNotification, WPARAM wParam, LPARAM lParam, LONG_PTR dwRefData)
{
    if (TDN_CREATED == uNotification) {
        SendMessage(hwnd, TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE, IDYES, TRUE);
    }

    return S_OK;
}

void CFileAssoc::CheckIconsAssocThread()
{
    UINT nLastVersion = AfxGetApp()->GetProfileInt(IDS_R_SETTINGS, IDS_RS_ICON_LIB_VERSION, 0);

    if (auto iconLib = GetIconLib()) {
        UINT nCurrentVersion = iconLib->GetVersion();

        CAtlList<CString> registeredExts;

        if (nCurrentVersion != nLastVersion && GetAssociatedExtensionsFromRegistry(registeredExts)) {
            iconLib->SaveVersion();
            if (!IsUserAnAdmin()) {
                TASKDIALOGCONFIG config;
                ZeroMemory(&config, sizeof(TASKDIALOGCONFIG));
                config.cbSize = sizeof(config);
                config.hInstance = AfxGetInstanceHandle();
                config.hwndParent = AfxGetApp()->GetMainWnd()->GetSafeHwnd();
                config.dwCommonButtons = TDCBF_YES_BUTTON | TDCBF_NO_BUTTON;
                config.pszMainIcon = TD_SHIELD_ICON;
                config.pszWindowTitle = MAKEINTRESOURCE(IDS_ICONS_REASSOC_DLG_TITLE);
                config.pszMainInstruction = MAKEINTRESOURCE(IDS_ICONS_REASSOC_DLG_INSTR);
                config.pszContent = MAKEINTRESOURCE(IDS_ICONS_REASSOC_DLG_CONTENT);
                config.pfCallback = TaskDialogCallbackProc;

                typedef HRESULT(_stdcall * pfTaskDialogIndirect)(const TASKDIALOGCONFIG*, int*, int*, BOOL*);

                HMODULE hModule = ::LoadLibrary(_T("comctl32.dll"));
                if (hModule) {
                    pfTaskDialogIndirect TaskDialogIndirect = (pfTaskDialogIndirect)(::GetProcAddress(hModule, "TaskDialogIndirect"));

                    if (TaskDialogIndirect) {
                        int nButtonPressed = 0;
                        TaskDialogIndirect(&config, &nButtonPressed, nullptr, nullptr);

                        if (IDYES == nButtonPressed) {
                            AfxGetMyApp()->RunAsAdministrator(PathUtils::GetProgramPath(true), _T("/iconsassoc"), true);
                        }
                    }

                    ::FreeLibrary(hModule);
                }
            } else {
                ReAssocIcons(registeredExts);

                SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nullptr, nullptr);
            }
        }
    }

    m_checkIconsAssocInactiveEvent.Set();
}

void CFileAssoc::CheckIconsAssoc()
{
    std::lock_guard<std::mutex> lock(m_checkIconsAssocMutex);
    HANDLE hEvent = m_checkIconsAssocInactiveEvent;
    DWORD dwEvent;
    VERIFY(CoWaitForMultipleHandles(0, INFINITE, 1, &hEvent, &dwEvent) == S_OK);
    m_checkIconsAssocInactiveEvent.Reset();
    std::thread(
        [this] { CheckIconsAssocThread(); }
    ).detach();
}

bool CFileAssoc::ShowWindowsAssocDialog() const
{
    IApplicationAssociationRegistrationUI* pAARUI;
    HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
                                  nullptr,
                                  CLSCTX_INPROC,
                                  IID_PPV_ARGS(&pAARUI));

    bool success = (SUCCEEDED(hr) && pAARUI != nullptr);

    if (success) {
        pAARUI->LaunchAdvancedAssociationUI(m_strRegisteredAppName);
        pAARUI->Release();
    }

    return success;
}