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