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