browser_win.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/browser.h"
  5. // must come before other includes. fixes bad #defines from <shlwapi.h>.
  6. #include "base/win/shlwapi.h" // NOLINT(build/include_order)
  7. #include <windows.h> // NOLINT(build/include_order)
  8. #include <atlbase.h> // NOLINT(build/include_order)
  9. #include <shlobj.h> // NOLINT(build/include_order)
  10. #include <shobjidl.h> // NOLINT(build/include_order)
  11. #include "base/base_paths.h"
  12. #include "base/file_version_info.h"
  13. #include "base/files/file_path.h"
  14. #include "base/logging.h"
  15. #include "base/path_service.h"
  16. #include "base/strings/string_util.h"
  17. #include "base/strings/stringprintf.h"
  18. #include "base/strings/utf_string_conversions.h"
  19. #include "base/threading/thread_restrictions.h"
  20. #include "base/win/registry.h"
  21. #include "base/win/win_util.h"
  22. #include "base/win/windows_version.h"
  23. #include "chrome/browser/icon_manager.h"
  24. #include "electron/electron_version.h"
  25. #include "shell/browser/api/electron_api_app.h"
  26. #include "shell/browser/badging/badge_manager.h"
  27. #include "shell/browser/electron_browser_main_parts.h"
  28. #include "shell/browser/ui/message_box.h"
  29. #include "shell/browser/ui/win/jump_list.h"
  30. #include "shell/browser/window_list.h"
  31. #include "shell/common/application_info.h"
  32. #include "shell/common/gin_converters/file_path_converter.h"
  33. #include "shell/common/gin_converters/image_converter.h"
  34. #include "shell/common/gin_helper/arguments.h"
  35. #include "shell/common/gin_helper/dictionary.h"
  36. #include "shell/common/skia_util.h"
  37. #include "skia/ext/legacy_display_globals.h"
  38. #include "third_party/skia/include/core/SkCanvas.h"
  39. #include "third_party/skia/include/core/SkFont.h"
  40. #include "third_party/skia/include/core/SkPaint.h"
  41. #include "ui/base/l10n/l10n_util.h"
  42. #include "ui/events/keycodes/keyboard_code_conversion_win.h"
  43. #include "ui/strings/grit/ui_strings.h"
  44. namespace electron {
  45. namespace {
  46. bool GetProcessExecPath(std::wstring* exe) {
  47. base::FilePath path;
  48. if (!base::PathService::Get(base::FILE_EXE, &path)) {
  49. return false;
  50. }
  51. *exe = path.value();
  52. return true;
  53. }
  54. bool GetProtocolLaunchPath(gin::Arguments* args, std::wstring* exe) {
  55. if (!args->GetNext(exe) && !GetProcessExecPath(exe)) {
  56. return false;
  57. }
  58. // Read in optional args arg
  59. std::vector<std::wstring> launch_args;
  60. if (args->GetNext(&launch_args) && !launch_args.empty())
  61. *exe = base::StringPrintf(L"\"%ls\" \"%ls\" \"%%1\"", exe->c_str(),
  62. base::JoinString(launch_args, L"\" \"").c_str());
  63. else
  64. *exe = base::StringPrintf(L"\"%ls\" \"%%1\"", exe->c_str());
  65. return true;
  66. }
  67. // Windows treats a given scheme as an Internet scheme only if its registry
  68. // entry has a "URL Protocol" key. Check this, otherwise we allow ProgIDs to be
  69. // used as custom protocols which leads to security bugs.
  70. bool IsValidCustomProtocol(const std::wstring& scheme) {
  71. if (scheme.empty())
  72. return false;
  73. base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, scheme.c_str(), KEY_QUERY_VALUE);
  74. return cmd_key.Valid() && cmd_key.HasValue(L"URL Protocol");
  75. }
  76. // Helper for GetApplicationInfoForProtocol().
  77. // takes in an assoc_str
  78. // (https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/ne-shlwapi-assocstr)
  79. // and returns the application name, icon and path that handles the protocol.
  80. //
  81. // Windows 8 introduced a new protocol->executable binding system which cannot
  82. // be retrieved in the HKCR registry subkey method implemented below. We call
  83. // AssocQueryString with the new Win8-only flag ASSOCF_IS_PROTOCOL instead.
  84. std::wstring GetAppInfoHelperForProtocol(ASSOCSTR assoc_str, const GURL& url) {
  85. const std::wstring url_scheme = base::ASCIIToWide(url.scheme());
  86. if (!IsValidCustomProtocol(url_scheme))
  87. return std::wstring();
  88. wchar_t out_buffer[1024];
  89. DWORD buffer_size = std::size(out_buffer);
  90. HRESULT hr =
  91. AssocQueryString(ASSOCF_IS_PROTOCOL, assoc_str, url_scheme.c_str(), NULL,
  92. out_buffer, &buffer_size);
  93. if (FAILED(hr)) {
  94. DLOG(WARNING) << "AssocQueryString failed!";
  95. return std::wstring();
  96. }
  97. return std::wstring(out_buffer);
  98. }
  99. void OnIconDataAvailable(const base::FilePath& app_path,
  100. const std::wstring& app_display_name,
  101. gin_helper::Promise<gin_helper::Dictionary> promise,
  102. gfx::Image icon) {
  103. if (!icon.IsEmpty()) {
  104. v8::HandleScope scope(promise.isolate());
  105. gin_helper::Dictionary dict =
  106. gin::Dictionary::CreateEmpty(promise.isolate());
  107. dict.Set("path", app_path);
  108. dict.Set("name", app_display_name);
  109. dict.Set("icon", icon);
  110. promise.Resolve(dict);
  111. } else {
  112. promise.RejectWithErrorMessage("Failed to get file icon.");
  113. }
  114. }
  115. std::wstring GetAppDisplayNameForProtocol(const GURL& url) {
  116. return GetAppInfoHelperForProtocol(ASSOCSTR_FRIENDLYAPPNAME, url);
  117. }
  118. std::wstring GetAppPathForProtocol(const GURL& url) {
  119. return GetAppInfoHelperForProtocol(ASSOCSTR_EXECUTABLE, url);
  120. }
  121. std::wstring GetAppForProtocolUsingRegistry(const GURL& url) {
  122. const std::wstring url_scheme = base::ASCIIToWide(url.scheme());
  123. if (!IsValidCustomProtocol(url_scheme))
  124. return std::wstring();
  125. // First, try and extract the application's display name.
  126. std::wstring command_to_launch;
  127. base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, url_scheme.c_str(),
  128. KEY_READ);
  129. if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS &&
  130. !command_to_launch.empty()) {
  131. return command_to_launch;
  132. }
  133. // Otherwise, parse the command line in the registry, and return the basename
  134. // of the program path if it exists.
  135. const std::wstring cmd_key_path = url_scheme + L"\\shell\\open\\command";
  136. base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
  137. KEY_READ);
  138. if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) {
  139. base::CommandLine command_line(
  140. base::CommandLine::FromString(command_to_launch));
  141. return command_line.GetProgram().BaseName().value();
  142. }
  143. return std::wstring();
  144. }
  145. bool FormatCommandLineString(std::wstring* exe,
  146. const std::vector<std::u16string>& launch_args) {
  147. if (exe->empty() && !GetProcessExecPath(exe)) {
  148. return false;
  149. }
  150. if (!launch_args.empty()) {
  151. std::u16string joined_launch_args = base::JoinString(launch_args, u" ");
  152. *exe = base::StringPrintf(L"%ls %ls", exe->c_str(),
  153. base::as_wcstr(joined_launch_args));
  154. }
  155. return true;
  156. }
  157. // Helper for GetLoginItemSettings().
  158. // iterates over all the entries in a windows registry path and returns
  159. // a list of launchItem with matching paths to our application.
  160. // if a launchItem with a matching path also has a matching entry within the
  161. // startup_approved_key_path, set executable_will_launch_at_login to be `true`
  162. std::vector<Browser::LaunchItem> GetLoginItemSettingsHelper(
  163. base::win::RegistryValueIterator* it,
  164. boolean* executable_will_launch_at_login,
  165. std::wstring scope,
  166. const Browser::LoginItemSettings& options) {
  167. std::vector<Browser::LaunchItem> launch_items;
  168. base::FilePath lookup_exe_path;
  169. if (options.path.empty()) {
  170. std::wstring process_exe_path;
  171. GetProcessExecPath(&process_exe_path);
  172. lookup_exe_path =
  173. base::CommandLine::FromString(process_exe_path).GetProgram();
  174. } else {
  175. lookup_exe_path =
  176. base::CommandLine::FromString(base::as_wcstr(options.path))
  177. .GetProgram();
  178. }
  179. if (!lookup_exe_path.empty()) {
  180. while (it->Valid()) {
  181. base::CommandLine registry_launch_cmd =
  182. base::CommandLine::FromString(it->Value());
  183. base::FilePath registry_launch_path = registry_launch_cmd.GetProgram();
  184. bool exe_match = base::FilePath::CompareEqualIgnoreCase(
  185. lookup_exe_path.value(), registry_launch_path.value());
  186. // add launch item to vector if it has a matching path (case-insensitive)
  187. if (exe_match) {
  188. Browser::LaunchItem launch_item;
  189. launch_item.name = it->Name();
  190. launch_item.path = registry_launch_path.value();
  191. launch_item.args = registry_launch_cmd.GetArgs();
  192. launch_item.scope = scope;
  193. launch_item.enabled = true;
  194. // attempt to update launch_item.enabled if there is a matching key
  195. // value entry in the StartupApproved registry
  196. HKEY hkey;
  197. // StartupApproved registry path
  198. LPCTSTR path = TEXT(
  199. "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp"
  200. "roved\\Run");
  201. LONG res;
  202. if (scope == L"user") {
  203. res =
  204. RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_QUERY_VALUE, &hkey);
  205. } else {
  206. res =
  207. RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hkey);
  208. }
  209. if (res == ERROR_SUCCESS) {
  210. DWORD type, size;
  211. wchar_t startup_binary[12];
  212. LONG result =
  213. RegQueryValueEx(hkey, it->Name(), nullptr, &type,
  214. reinterpret_cast<BYTE*>(&startup_binary),
  215. &(size = sizeof(startup_binary)));
  216. if (result == ERROR_SUCCESS) {
  217. if (type == REG_BINARY) {
  218. // any other binary other than this indicates that the program is
  219. // not set to launch at login
  220. wchar_t binary_accepted[12] = {0x00, 0x00, 0x00, 0x00,
  221. 0x00, 0x00, 0x00, 0x00,
  222. 0x00, 0x00, 0x00, 0x00};
  223. wchar_t binary_accepted_alt[12] = {0x02, 0x00, 0x00, 0x00,
  224. 0x00, 0x00, 0x00, 0x00,
  225. 0x00, 0x00, 0x00, 0x00};
  226. std::string reg_binary(reinterpret_cast<char*>(binary_accepted));
  227. std::string reg_binary_alt(
  228. reinterpret_cast<char*>(binary_accepted_alt));
  229. std::string reg_startup_binary(
  230. reinterpret_cast<char*>(startup_binary));
  231. launch_item.enabled = (reg_startup_binary == reg_binary) ||
  232. (reg_startup_binary == reg_binary_alt);
  233. }
  234. }
  235. }
  236. *executable_will_launch_at_login =
  237. *executable_will_launch_at_login || launch_item.enabled;
  238. launch_items.push_back(launch_item);
  239. }
  240. it->operator++();
  241. }
  242. }
  243. return launch_items;
  244. }
  245. std::unique_ptr<FileVersionInfo> FetchFileVersionInfo() {
  246. base::FilePath path;
  247. if (base::PathService::Get(base::FILE_EXE, &path)) {
  248. base::ThreadRestrictions::ScopedAllowIO allow_io;
  249. return FileVersionInfo::CreateFileVersionInfo(path);
  250. }
  251. return std::unique_ptr<FileVersionInfo>();
  252. }
  253. } // namespace
  254. Browser::UserTask::UserTask() = default;
  255. Browser::UserTask::UserTask(const UserTask&) = default;
  256. Browser::UserTask::~UserTask() = default;
  257. void GetFileIcon(const base::FilePath& path,
  258. v8::Isolate* isolate,
  259. base::CancelableTaskTracker* cancelable_task_tracker_,
  260. const std::wstring app_display_name,
  261. gin_helper::Promise<gin_helper::Dictionary> promise) {
  262. base::FilePath normalized_path = path.NormalizePathSeparators();
  263. IconLoader::IconSize icon_size = IconLoader::IconSize::LARGE;
  264. auto* icon_manager = ElectronBrowserMainParts::Get()->GetIconManager();
  265. gfx::Image* icon =
  266. icon_manager->LookupIconFromFilepath(normalized_path, icon_size, 1.0f);
  267. if (icon) {
  268. gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
  269. dict.Set("icon", *icon);
  270. dict.Set("name", app_display_name);
  271. dict.Set("path", normalized_path);
  272. promise.Resolve(dict);
  273. } else {
  274. icon_manager->LoadIcon(normalized_path, icon_size, 1.0f,
  275. base::BindOnce(&OnIconDataAvailable, normalized_path,
  276. app_display_name, std::move(promise)),
  277. cancelable_task_tracker_);
  278. }
  279. }
  280. void GetApplicationInfoForProtocolUsingRegistry(
  281. v8::Isolate* isolate,
  282. const GURL& url,
  283. gin_helper::Promise<gin_helper::Dictionary> promise,
  284. base::CancelableTaskTracker* cancelable_task_tracker_) {
  285. base::FilePath app_path;
  286. const std::wstring url_scheme = base::ASCIIToWide(url.scheme());
  287. if (!IsValidCustomProtocol(url_scheme)) {
  288. promise.RejectWithErrorMessage("invalid url_scheme");
  289. return;
  290. }
  291. std::wstring command_to_launch;
  292. const std::wstring cmd_key_path = url_scheme + L"\\shell\\open\\command";
  293. base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
  294. KEY_READ);
  295. if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) {
  296. base::CommandLine command_line(
  297. base::CommandLine::FromString(command_to_launch));
  298. app_path = command_line.GetProgram();
  299. } else {
  300. promise.RejectWithErrorMessage(
  301. "Unable to retrieve installation path to app");
  302. return;
  303. }
  304. const std::wstring app_display_name = GetAppForProtocolUsingRegistry(url);
  305. if (app_display_name.empty()) {
  306. promise.RejectWithErrorMessage(
  307. "Unable to retrieve application display name");
  308. return;
  309. }
  310. GetFileIcon(app_path, isolate, cancelable_task_tracker_, app_display_name,
  311. std::move(promise));
  312. }
  313. // resolves `Promise<Object>` - Resolve with an object containing the following:
  314. // * `icon` NativeImage - the display icon of the app handling the protocol.
  315. // * `path` String - installation path of the app handling the protocol.
  316. // * `name` String - display name of the app handling the protocol.
  317. void GetApplicationInfoForProtocolUsingAssocQuery(
  318. v8::Isolate* isolate,
  319. const GURL& url,
  320. gin_helper::Promise<gin_helper::Dictionary> promise,
  321. base::CancelableTaskTracker* cancelable_task_tracker_) {
  322. std::wstring app_path = GetAppPathForProtocol(url);
  323. if (app_path.empty()) {
  324. promise.RejectWithErrorMessage(
  325. "Unable to retrieve installation path to app");
  326. return;
  327. }
  328. std::wstring app_display_name = GetAppDisplayNameForProtocol(url);
  329. if (app_display_name.empty()) {
  330. promise.RejectWithErrorMessage("Unable to retrieve display name of app");
  331. return;
  332. }
  333. base::FilePath app_path_file_path = base::FilePath(app_path);
  334. GetFileIcon(app_path_file_path, isolate, cancelable_task_tracker_,
  335. app_display_name, std::move(promise));
  336. }
  337. void Browser::AddRecentDocument(const base::FilePath& path) {
  338. CComPtr<IShellItem> item;
  339. HRESULT hr = SHCreateItemFromParsingName(path.value().c_str(), NULL,
  340. IID_PPV_ARGS(&item));
  341. if (SUCCEEDED(hr)) {
  342. SHARDAPPIDINFO info;
  343. info.psi = item;
  344. info.pszAppID = GetAppUserModelID();
  345. SHAddToRecentDocs(SHARD_APPIDINFO, &info);
  346. }
  347. }
  348. void Browser::ClearRecentDocuments() {
  349. SHAddToRecentDocs(SHARD_APPIDINFO, nullptr);
  350. }
  351. void Browser::SetAppUserModelID(const std::wstring& name) {
  352. electron::SetAppUserModelID(name);
  353. }
  354. bool Browser::SetUserTasks(const std::vector<UserTask>& tasks) {
  355. JumpList jump_list(GetAppUserModelID());
  356. if (!jump_list.Begin())
  357. return false;
  358. JumpListCategory category;
  359. category.type = JumpListCategory::Type::kTasks;
  360. category.items.reserve(tasks.size());
  361. JumpListItem item;
  362. item.type = JumpListItem::Type::kTask;
  363. for (const auto& task : tasks) {
  364. item.title = task.title;
  365. item.path = task.program;
  366. item.arguments = task.arguments;
  367. item.icon_path = task.icon_path;
  368. item.icon_index = task.icon_index;
  369. item.description = task.description;
  370. item.working_dir = task.working_dir;
  371. category.items.push_back(item);
  372. }
  373. jump_list.AppendCategory(category);
  374. return jump_list.Commit();
  375. }
  376. bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
  377. gin::Arguments* args) {
  378. if (protocol.empty())
  379. return false;
  380. // Main Registry Key
  381. HKEY root = HKEY_CURRENT_USER;
  382. std::wstring keyPath = L"Software\\Classes\\";
  383. // Command Key
  384. std::wstring wprotocol = base::UTF8ToWide(protocol);
  385. std::wstring shellPath = wprotocol + L"\\shell";
  386. std::wstring cmdPath = keyPath + shellPath + L"\\open\\command";
  387. base::win::RegKey classesKey;
  388. base::win::RegKey commandKey;
  389. if (FAILED(classesKey.Open(root, keyPath.c_str(), KEY_ALL_ACCESS)))
  390. // Classes key doesn't exist, that's concerning, but I guess
  391. // we're not the default handler
  392. return true;
  393. if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS)))
  394. // Key doesn't even exist, we can confirm that it is not set
  395. return true;
  396. std::wstring keyVal;
  397. if (FAILED(commandKey.ReadValue(L"", &keyVal)))
  398. // Default value not set, we can confirm that it is not set
  399. return true;
  400. std::wstring exe;
  401. if (!GetProtocolLaunchPath(args, &exe))
  402. return false;
  403. if (keyVal == exe) {
  404. // Let's kill the key
  405. if (FAILED(classesKey.DeleteKey(shellPath.c_str())))
  406. return false;
  407. // Let's clean up after ourselves
  408. base::win::RegKey protocolKey;
  409. std::wstring protocolPath = keyPath + wprotocol;
  410. if (SUCCEEDED(
  411. protocolKey.Open(root, protocolPath.c_str(), KEY_ALL_ACCESS))) {
  412. protocolKey.DeleteValue(L"URL Protocol");
  413. // Overwrite the default value to be empty, we can't delete it right away
  414. protocolKey.WriteValue(L"", L"");
  415. protocolKey.DeleteValue(L"");
  416. }
  417. // If now empty, delete the whole key
  418. classesKey.DeleteEmptyKey(wprotocol.c_str());
  419. return true;
  420. } else {
  421. return true;
  422. }
  423. }
  424. bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
  425. gin::Arguments* args) {
  426. // HKEY_CLASSES_ROOT
  427. // $PROTOCOL
  428. // (Default) = "URL:$NAME"
  429. // URL Protocol = ""
  430. // shell
  431. // open
  432. // command
  433. // (Default) = "$COMMAND" "%1"
  434. //
  435. // However, the "HKEY_CLASSES_ROOT" key can only be written by the
  436. // Administrator user. So, we instead write to "HKEY_CURRENT_USER\
  437. // Software\Classes", which is inherited by "HKEY_CLASSES_ROOT"
  438. // anyway, and can be written by unprivileged users.
  439. if (protocol.empty())
  440. return false;
  441. std::wstring exe;
  442. if (!GetProtocolLaunchPath(args, &exe))
  443. return false;
  444. // Main Registry Key
  445. HKEY root = HKEY_CURRENT_USER;
  446. std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol);
  447. std::wstring urlDecl = base::UTF8ToWide("URL:" + protocol);
  448. // Command Key
  449. std::wstring cmdPath = keyPath + L"\\shell\\open\\command";
  450. // Write information to registry
  451. base::win::RegKey key(root, keyPath.c_str(), KEY_ALL_ACCESS);
  452. if (FAILED(key.WriteValue(L"URL Protocol", L"")) ||
  453. FAILED(key.WriteValue(L"", urlDecl.c_str())))
  454. return false;
  455. base::win::RegKey commandKey(root, cmdPath.c_str(), KEY_ALL_ACCESS);
  456. if (FAILED(commandKey.WriteValue(L"", exe.c_str())))
  457. return false;
  458. return true;
  459. }
  460. bool Browser::IsDefaultProtocolClient(const std::string& protocol,
  461. gin::Arguments* args) {
  462. if (protocol.empty())
  463. return false;
  464. std::wstring exe;
  465. if (!GetProtocolLaunchPath(args, &exe))
  466. return false;
  467. // Main Registry Key
  468. HKEY root = HKEY_CURRENT_USER;
  469. std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol);
  470. // Command Key
  471. std::wstring cmdPath = keyPath + L"\\shell\\open\\command";
  472. base::win::RegKey key;
  473. base::win::RegKey commandKey;
  474. if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS)))
  475. // Key doesn't exist, we can confirm that it is not set
  476. return false;
  477. if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS)))
  478. // Key doesn't exist, we can confirm that it is not set
  479. return false;
  480. std::wstring keyVal;
  481. if (FAILED(commandKey.ReadValue(L"", &keyVal)))
  482. // Default value not set, we can confirm that it is not set
  483. return false;
  484. // Default value is the same as current file path
  485. return keyVal == exe;
  486. }
  487. std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
  488. // Windows 8 or above has a new protocol association query.
  489. if (base::win::GetVersion() >= base::win::Version::WIN8) {
  490. std::wstring application_name = GetAppDisplayNameForProtocol(url);
  491. if (!application_name.empty())
  492. return base::WideToUTF16(application_name);
  493. }
  494. return base::WideToUTF16(GetAppForProtocolUsingRegistry(url));
  495. }
  496. v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
  497. v8::Isolate* isolate,
  498. const GURL& url) {
  499. gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
  500. v8::Local<v8::Promise> handle = promise.GetHandle();
  501. // Windows 8 or above has a new protocol association query.
  502. if (base::win::GetVersion() >= base::win::Version::WIN8) {
  503. GetApplicationInfoForProtocolUsingAssocQuery(
  504. isolate, url, std::move(promise), &cancelable_task_tracker_);
  505. return handle;
  506. }
  507. GetApplicationInfoForProtocolUsingRegistry(isolate, url, std::move(promise),
  508. &cancelable_task_tracker_);
  509. return handle;
  510. }
  511. bool Browser::SetBadgeCount(absl::optional<int> count) {
  512. absl::optional<std::string> badge_content;
  513. if (count.has_value() && count.value() == 0) {
  514. badge_content = absl::nullopt;
  515. } else {
  516. badge_content = badging::BadgeManager::GetBadgeString(count);
  517. }
  518. // There are 3 different cases when the badge has a value:
  519. // 1. |contents| is between 1 and 99 inclusive => Set the accessibility text
  520. // to a pluralized notification count (e.g. 4 Unread Notifications).
  521. // 2. |contents| is greater than 99 => Set the accessibility text to
  522. // More than |kMaxBadgeContent| unread notifications, so the
  523. // accessibility text matches what is displayed on the badge (e.g. More
  524. // than 99 notifications).
  525. // 3. The badge is set to 'flag' => Set the accessibility text to something
  526. // less specific (e.g. Unread Notifications).
  527. std::string badge_alt_string;
  528. if (count.has_value()) {
  529. badge_count_ = count.value();
  530. badge_alt_string = (uint64_t)badge_count_ <= badging::kMaxBadgeContent
  531. // Case 1.
  532. ? l10n_util::GetPluralStringFUTF8(
  533. IDS_BADGE_UNREAD_NOTIFICATIONS, badge_count_)
  534. // Case 2.
  535. : l10n_util::GetPluralStringFUTF8(
  536. IDS_BADGE_UNREAD_NOTIFICATIONS_SATURATED,
  537. badging::kMaxBadgeContent);
  538. } else {
  539. // Case 3.
  540. badge_alt_string =
  541. l10n_util::GetStringUTF8(IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED);
  542. badge_count_ = 0;
  543. }
  544. for (auto* window : WindowList::GetWindows()) {
  545. // On Windows set the badge on the first window found.
  546. UpdateBadgeContents(window->GetAcceleratedWidget(), badge_content,
  547. badge_alt_string);
  548. }
  549. return true;
  550. }
  551. void Browser::UpdateBadgeContents(
  552. HWND hwnd,
  553. const absl::optional<std::string>& badge_content,
  554. const std::string& badge_alt_string) {
  555. SkBitmap badge;
  556. if (badge_content) {
  557. std::string content = badge_content.value();
  558. constexpr int kOverlayIconSize = 16;
  559. // This is the color used by the Windows 10 Badge API, for platform
  560. // consistency.
  561. constexpr int kBackgroundColor = SkColorSetRGB(0x26, 0x25, 0x2D);
  562. constexpr int kForegroundColor = SK_ColorWHITE;
  563. constexpr int kRadius = kOverlayIconSize / 2;
  564. // The minimum gap to have between our content and the edge of the badge.
  565. constexpr int kMinMargin = 3;
  566. // The amount of space we have to render the icon.
  567. constexpr int kMaxBounds = kOverlayIconSize - 2 * kMinMargin;
  568. constexpr int kMaxTextSize = 24; // Max size for our text.
  569. constexpr int kMinTextSize = 7; // Min size for our text.
  570. badge.allocN32Pixels(kOverlayIconSize, kOverlayIconSize);
  571. SkCanvas canvas(badge, skia::LegacyDisplayGlobals::GetSkSurfaceProps());
  572. SkPaint paint;
  573. paint.setAntiAlias(true);
  574. paint.setColor(kBackgroundColor);
  575. canvas.clear(SK_ColorTRANSPARENT);
  576. canvas.drawCircle(kRadius, kRadius, kRadius, paint);
  577. paint.reset();
  578. paint.setColor(kForegroundColor);
  579. SkFont font;
  580. SkRect bounds;
  581. int text_size = kMaxTextSize;
  582. // Find the largest |text_size| larger than |kMinTextSize| in which
  583. // |content| fits into our 16x16px icon, with margins.
  584. do {
  585. font.setSize(text_size--);
  586. font.measureText(content.c_str(), content.size(), SkTextEncoding::kUTF8,
  587. &bounds);
  588. } while (text_size >= kMinTextSize &&
  589. (bounds.width() > kMaxBounds || bounds.height() > kMaxBounds));
  590. canvas.drawSimpleText(
  591. content.c_str(), content.size(), SkTextEncoding::kUTF8,
  592. kRadius - bounds.width() / 2 - bounds.x(),
  593. kRadius - bounds.height() / 2 - bounds.y(), font, paint);
  594. }
  595. taskbar_host_.SetOverlayIcon(hwnd, badge, badge_alt_string);
  596. }
  597. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  598. std::wstring key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  599. base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_ALL_ACCESS);
  600. std::wstring startup_approved_key_path =
  601. L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved"
  602. L"\\Run";
  603. base::win::RegKey startup_approved_key(
  604. HKEY_CURRENT_USER, startup_approved_key_path.c_str(), KEY_ALL_ACCESS);
  605. PCWSTR key_name =
  606. !settings.name.empty() ? settings.name.c_str() : GetAppUserModelID();
  607. if (settings.open_at_login) {
  608. std::wstring exe = base::UTF16ToWide(settings.path);
  609. if (FormatCommandLineString(&exe, settings.args)) {
  610. key.WriteValue(key_name, exe.c_str());
  611. if (settings.enabled) {
  612. startup_approved_key.DeleteValue(key_name);
  613. } else {
  614. HKEY hard_key;
  615. LPCTSTR path = TEXT(
  616. "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp"
  617. "roved\\Run");
  618. LONG res =
  619. RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hard_key);
  620. if (res == ERROR_SUCCESS) {
  621. UCHAR disable_startup_binary[] = {0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
  622. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  623. RegSetValueEx(hard_key, key_name, 0, REG_BINARY,
  624. reinterpret_cast<const BYTE*>(disable_startup_binary),
  625. sizeof(disable_startup_binary));
  626. }
  627. }
  628. }
  629. } else {
  630. // if open at login is false, delete both values
  631. startup_approved_key.DeleteValue(key_name);
  632. key.DeleteValue(key_name);
  633. }
  634. }
  635. Browser::LoginItemSettings Browser::GetLoginItemSettings(
  636. const LoginItemSettings& options) {
  637. LoginItemSettings settings;
  638. std::wstring keyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  639. base::win::RegKey key(HKEY_CURRENT_USER, keyPath.c_str(), KEY_ALL_ACCESS);
  640. std::wstring keyVal;
  641. // keep old openAtLogin behaviour
  642. if (!FAILED(key.ReadValue(GetAppUserModelID(), &keyVal))) {
  643. std::wstring exe = base::UTF16ToWide(options.path);
  644. if (FormatCommandLineString(&exe, options.args)) {
  645. settings.open_at_login = keyVal == exe;
  646. }
  647. }
  648. // iterate over current user and machine registries and populate launch items
  649. // if there exists a launch entry with property enabled=='true',
  650. // set executable_will_launch_at_login to 'true'.
  651. boolean executable_will_launch_at_login = false;
  652. std::vector<Browser::LaunchItem> launch_items;
  653. base::win::RegistryValueIterator hkcu_iterator(HKEY_CURRENT_USER,
  654. keyPath.c_str());
  655. base::win::RegistryValueIterator hklm_iterator(HKEY_LOCAL_MACHINE,
  656. keyPath.c_str());
  657. launch_items = GetLoginItemSettingsHelper(
  658. &hkcu_iterator, &executable_will_launch_at_login, L"user", options);
  659. std::vector<Browser::LaunchItem> launch_items_hklm =
  660. GetLoginItemSettingsHelper(&hklm_iterator,
  661. &executable_will_launch_at_login, L"machine",
  662. options);
  663. launch_items.insert(launch_items.end(), launch_items_hklm.begin(),
  664. launch_items_hklm.end());
  665. settings.executable_will_launch_at_login = executable_will_launch_at_login;
  666. settings.launch_items = launch_items;
  667. return settings;
  668. }
  669. PCWSTR Browser::GetAppUserModelID() {
  670. return GetRawAppUserModelID();
  671. }
  672. std::string Browser::GetExecutableFileVersion() const {
  673. base::FilePath path;
  674. if (base::PathService::Get(base::FILE_EXE, &path)) {
  675. base::ThreadRestrictions::ScopedAllowIO allow_io;
  676. std::unique_ptr<FileVersionInfo> version_info = FetchFileVersionInfo();
  677. return base::UTF16ToUTF8(version_info->product_version());
  678. }
  679. return ELECTRON_VERSION_STRING;
  680. }
  681. std::string Browser::GetExecutableFileProductName() const {
  682. return GetApplicationName();
  683. }
  684. bool Browser::IsEmojiPanelSupported() {
  685. // emoji picker is supported on Windows 10's Spring 2018 update & above.
  686. return base::win::GetVersion() >= base::win::Version::WIN10_RS4;
  687. }
  688. void Browser::ShowEmojiPanel() {
  689. // This sends Windows Key + '.' (both keydown and keyup events).
  690. // "SendInput" is used because Windows needs to receive these events and
  691. // open the Emoji picker.
  692. INPUT input[4] = {};
  693. input[0].type = INPUT_KEYBOARD;
  694. input[0].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND);
  695. input[1].type = INPUT_KEYBOARD;
  696. input[1].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD);
  697. input[2].type = INPUT_KEYBOARD;
  698. input[2].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND);
  699. input[2].ki.dwFlags |= KEYEVENTF_KEYUP;
  700. input[3].type = INPUT_KEYBOARD;
  701. input[3].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD);
  702. input[3].ki.dwFlags |= KEYEVENTF_KEYUP;
  703. ::SendInput(4, input, sizeof(INPUT));
  704. }
  705. void Browser::ShowAboutPanel() {
  706. base::Value dict(base::Value::Type::DICTIONARY);
  707. std::string aboutMessage = "";
  708. gfx::ImageSkia image;
  709. // grab defaults from Windows .EXE file
  710. std::unique_ptr<FileVersionInfo> exe_info = FetchFileVersionInfo();
  711. dict.SetStringKey("applicationName", exe_info->file_description());
  712. dict.SetStringKey("applicationVersion", exe_info->product_version());
  713. if (about_panel_options_.is_dict()) {
  714. dict.MergeDictionary(&about_panel_options_);
  715. }
  716. std::vector<std::string> stringOptions = {
  717. "applicationName", "applicationVersion", "copyright", "credits"};
  718. const std::string* str;
  719. for (std::string opt : stringOptions) {
  720. if ((str = dict.FindStringKey(opt))) {
  721. aboutMessage.append(*str).append("\r\n");
  722. }
  723. }
  724. if ((str = dict.FindStringKey("iconPath"))) {
  725. base::FilePath path = base::FilePath::FromUTF8Unsafe(*str);
  726. electron::util::PopulateImageSkiaRepsFromPath(&image, path);
  727. }
  728. electron::MessageBoxSettings settings = {};
  729. settings.message = aboutMessage;
  730. settings.icon = image;
  731. settings.type = electron::MessageBoxType::kInformation;
  732. electron::ShowMessageBoxSync(settings);
  733. }
  734. void Browser::SetAboutPanelOptions(base::Value::Dict options) {
  735. about_panel_options_ = base::Value(std::move(options));
  736. }
  737. } // namespace electron