browser_win.cc 31 KB

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