browser_win.cc 28 KB

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