1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/win/default_apps_util.h"
6
7 #include <shobjidl.h>
8 #include <wrl/client.h>
9
10 #include <string_view>
11
12 #include "base/logging.h"
13 #include "base/strings/strcat.h"
14 #include "base/strings/string_util.h"
15 #include "base/win/windows_version.h"
16
17 namespace {
18
19 // Returns the target used as a activate parameter when opening the settings
20 // pointing to the page that is the most relevant to a user trying to change the
21 // default handler for `protocol`.
GetTargetForDefaultAppsSettings(std::wstring_view protocol)22 std::wstring GetTargetForDefaultAppsSettings(std::wstring_view protocol) {
23 static constexpr std::wstring_view kSystemSettingsDefaultAppsPrefix(
24 L"SystemSettings_DefaultApps_");
25 if (base::EqualsCaseInsensitiveASCII(protocol, L"http"))
26 return base::StrCat({kSystemSettingsDefaultAppsPrefix, L"Browser"});
27 if (base::EqualsCaseInsensitiveASCII(protocol, L"mailto"))
28 return base::StrCat({kSystemSettingsDefaultAppsPrefix, L"Email"});
29 return L"SettingsPageAppsDefaultsProtocolView";
30 }
31
32 } // namespace
33
34 namespace base::win {
35
LaunchDefaultAppsSettingsModernDialog(std::wstring_view protocol)36 bool LaunchDefaultAppsSettingsModernDialog(std::wstring_view protocol) {
37 // The appModelId looks arbitrary but it is the same in Win8 and Win10. There
38 // is no easy way to retrieve the appModelId from the registry.
39 static constexpr wchar_t kControlPanelAppModelId[] =
40 L"windows.immersivecontrolpanel_cw5n1h2txyewy"
41 L"!microsoft.windows.immersivecontrolpanel";
42
43 Microsoft::WRL::ComPtr<IApplicationActivationManager> activator;
44 HRESULT hr = ::CoCreateInstance(CLSID_ApplicationActivationManager, nullptr,
45 CLSCTX_ALL, IID_PPV_ARGS(&activator));
46 if (FAILED(hr))
47 return false;
48
49 DWORD pid = 0;
50 CoAllowSetForegroundWindow(activator.Get(), nullptr);
51 hr = activator->ActivateApplication(
52 kControlPanelAppModelId, L"page=SettingsPageAppsDefaults", AO_NONE, &pid);
53 if (FAILED(hr))
54 return false;
55 if (protocol.empty())
56 return true;
57
58 hr = activator->ActivateApplication(
59 kControlPanelAppModelId,
60 base::StrCat({L"page=SettingsPageAppsDefaults&target=",
61 GetTargetForDefaultAppsSettings(protocol)})
62 .c_str(),
63 AO_NONE, &pid);
64 return SUCCEEDED(hr);
65 }
66
67 } // namespace base::win
68