browser_win.cc 28 KB

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