browser_win.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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/string_util.h"
  18. #include "base/strings/stringprintf.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/legacy_display_globals.h"
  39. #include "third_party/skia/include/core/SkCanvas.h"
  40. #include "third_party/skia/include/core/SkFont.h"
  41. #include "third_party/skia/include/core/SkPaint.h"
  42. #include "ui/base/l10n/l10n_util.h"
  43. #include "ui/events/keycodes/keyboard_code_conversion_win.h"
  44. #include "ui/strings/grit/ui_strings.h"
  45. namespace electron {
  46. namespace {
  47. bool GetProcessExecPath(std::wstring* exe) {
  48. base::FilePath path;
  49. if (!base::PathService::Get(base::FILE_EXE, &path)) {
  50. return false;
  51. }
  52. *exe = path.value();
  53. return true;
  54. }
  55. bool GetProtocolLaunchPath(gin::Arguments* args, std::wstring* exe) {
  56. if (!args->GetNext(exe) && !GetProcessExecPath(exe)) {
  57. return false;
  58. }
  59. // Read in optional args arg
  60. std::vector<std::wstring> launch_args;
  61. if (args->GetNext(&launch_args) && !launch_args.empty())
  62. *exe = base::StringPrintf(L"\"%ls\" \"%ls\" \"%%1\"", exe->c_str(),
  63. base::JoinString(launch_args, L"\" \"").c_str());
  64. else
  65. *exe = base::StringPrintf(L"\"%ls\" \"%%1\"", exe->c_str());
  66. return true;
  67. }
  68. // Windows treats a given scheme as an Internet scheme only if its registry
  69. // entry has a "URL Protocol" key. Check this, otherwise we allow ProgIDs to be
  70. // used as custom protocols which leads to security bugs.
  71. bool IsValidCustomProtocol(const std::wstring& scheme) {
  72. if (scheme.empty())
  73. return false;
  74. base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, scheme.c_str(), KEY_QUERY_VALUE);
  75. return cmd_key.Valid() && cmd_key.HasValue(L"URL Protocol");
  76. }
  77. // Helper for GetApplicationInfoForProtocol().
  78. // takes in an assoc_str
  79. // (https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/ne-shlwapi-assocstr)
  80. // and returns the application name, icon and path that handles the protocol.
  81. std::wstring GetAppInfoHelperForProtocol(ASSOCSTR assoc_str, const GURL& url) {
  82. const std::wstring url_scheme = base::ASCIIToWide(url.scheme());
  83. if (!IsValidCustomProtocol(url_scheme))
  84. return std::wstring();
  85. wchar_t out_buffer[1024];
  86. DWORD buffer_size = std::size(out_buffer);
  87. HRESULT hr =
  88. AssocQueryString(ASSOCF_IS_PROTOCOL, assoc_str, url_scheme.c_str(), NULL,
  89. out_buffer, &buffer_size);
  90. if (FAILED(hr)) {
  91. DLOG(WARNING) << "AssocQueryString failed!";
  92. return std::wstring();
  93. }
  94. return std::wstring(out_buffer);
  95. }
  96. void OnIconDataAvailable(const base::FilePath& app_path,
  97. const std::wstring& app_display_name,
  98. gin_helper::Promise<gin_helper::Dictionary> promise,
  99. gfx::Image icon) {
  100. if (!icon.IsEmpty()) {
  101. v8::HandleScope scope(promise.isolate());
  102. gin_helper::Dictionary dict =
  103. gin::Dictionary::CreateEmpty(promise.isolate());
  104. dict.Set("path", app_path);
  105. dict.Set("name", app_display_name);
  106. dict.Set("icon", icon);
  107. promise.Resolve(dict);
  108. } else {
  109. promise.RejectWithErrorMessage("Failed to get file icon.");
  110. }
  111. }
  112. std::wstring GetAppDisplayNameForProtocol(const GURL& url) {
  113. return GetAppInfoHelperForProtocol(ASSOCSTR_FRIENDLYAPPNAME, url);
  114. }
  115. std::wstring GetAppPathForProtocol(const GURL& url) {
  116. return GetAppInfoHelperForProtocol(ASSOCSTR_EXECUTABLE, url);
  117. }
  118. bool FormatCommandLineString(std::wstring* exe,
  119. const std::vector<std::u16string>& launch_args) {
  120. if (exe->empty() && !GetProcessExecPath(exe)) {
  121. return false;
  122. }
  123. if (!launch_args.empty()) {
  124. std::u16string joined_launch_args = base::JoinString(launch_args, u" ");
  125. *exe = base::StringPrintf(L"%ls %ls", exe->c_str(),
  126. base::as_wcstr(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. gin_helper::Dictionary dict = gin::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(), NULL,
  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. classesKey.DeleteEmptyKey(wprotocol.c_str());
  359. return true;
  360. } else {
  361. return true;
  362. }
  363. }
  364. bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
  365. gin::Arguments* args) {
  366. // HKEY_CLASSES_ROOT
  367. // $PROTOCOL
  368. // (Default) = "URL:$NAME"
  369. // URL Protocol = ""
  370. // shell
  371. // open
  372. // command
  373. // (Default) = "$COMMAND" "%1"
  374. //
  375. // However, the "HKEY_CLASSES_ROOT" key can only be written by the
  376. // Administrator user. So, we instead write to "HKEY_CURRENT_USER\
  377. // Software\Classes", which is inherited by "HKEY_CLASSES_ROOT"
  378. // anyway, and can be written by unprivileged users.
  379. if (protocol.empty())
  380. return false;
  381. std::wstring exe;
  382. if (!GetProtocolLaunchPath(args, &exe))
  383. return false;
  384. // Main Registry Key
  385. HKEY root = HKEY_CURRENT_USER;
  386. std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol);
  387. std::wstring urlDecl = base::UTF8ToWide("URL:" + protocol);
  388. // Command Key
  389. std::wstring cmdPath = keyPath + L"\\shell\\open\\command";
  390. // Write information to registry
  391. base::win::RegKey key(root, keyPath.c_str(), KEY_ALL_ACCESS);
  392. if (FAILED(key.WriteValue(L"URL Protocol", L"")) ||
  393. FAILED(key.WriteValue(L"", urlDecl.c_str())))
  394. return false;
  395. base::win::RegKey commandKey(root, cmdPath.c_str(), KEY_ALL_ACCESS);
  396. if (FAILED(commandKey.WriteValue(L"", exe.c_str())))
  397. return false;
  398. return true;
  399. }
  400. bool Browser::IsDefaultProtocolClient(const std::string& protocol,
  401. gin::Arguments* args) {
  402. if (protocol.empty())
  403. return false;
  404. std::wstring exe;
  405. if (!GetProtocolLaunchPath(args, &exe))
  406. return false;
  407. // Main Registry Key
  408. HKEY root = HKEY_CURRENT_USER;
  409. std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol);
  410. // Command Key
  411. std::wstring cmdPath = keyPath + L"\\shell\\open\\command";
  412. base::win::RegKey key;
  413. base::win::RegKey commandKey;
  414. if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS)))
  415. // Key doesn't exist, we can confirm that it is not set
  416. return false;
  417. if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS)))
  418. // Key doesn't exist, we can confirm that it is not set
  419. return false;
  420. std::wstring keyVal;
  421. if (FAILED(commandKey.ReadValue(L"", &keyVal)))
  422. // Default value not set, we can confirm that it is not set
  423. return false;
  424. // Default value is the same as current file path
  425. return keyVal == exe;
  426. }
  427. std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
  428. return base::WideToUTF16(GetAppDisplayNameForProtocol(url));
  429. }
  430. v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
  431. v8::Isolate* isolate,
  432. const GURL& url) {
  433. gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
  434. v8::Local<v8::Promise> handle = promise.GetHandle();
  435. GetApplicationInfoForProtocolUsingAssocQuery(isolate, url, std::move(promise),
  436. &cancelable_task_tracker_);
  437. return handle;
  438. }
  439. bool Browser::SetBadgeCount(absl::optional<int> count) {
  440. absl::optional<std::string> badge_content;
  441. if (count.has_value() && count.value() == 0) {
  442. badge_content = absl::nullopt;
  443. } else {
  444. badge_content = badging::BadgeManager::GetBadgeString(count);
  445. }
  446. // There are 3 different cases when the badge has a value:
  447. // 1. |contents| is between 1 and 99 inclusive => Set the accessibility text
  448. // to a pluralized notification count (e.g. 4 Unread Notifications).
  449. // 2. |contents| is greater than 99 => Set the accessibility text to
  450. // More than |kMaxBadgeContent| unread notifications, so the
  451. // accessibility text matches what is displayed on the badge (e.g. More
  452. // than 99 notifications).
  453. // 3. The badge is set to 'flag' => Set the accessibility text to something
  454. // less specific (e.g. Unread Notifications).
  455. std::string badge_alt_string;
  456. if (count.has_value()) {
  457. badge_count_ = count.value();
  458. badge_alt_string = (uint64_t)badge_count_ <= badging::kMaxBadgeContent
  459. // Case 1.
  460. ? l10n_util::GetPluralStringFUTF8(
  461. IDS_BADGE_UNREAD_NOTIFICATIONS, badge_count_)
  462. // Case 2.
  463. : l10n_util::GetPluralStringFUTF8(
  464. IDS_BADGE_UNREAD_NOTIFICATIONS_SATURATED,
  465. badging::kMaxBadgeContent);
  466. } else {
  467. // Case 3.
  468. badge_alt_string =
  469. l10n_util::GetStringUTF8(IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED);
  470. badge_count_ = 0;
  471. }
  472. for (auto* window : WindowList::GetWindows()) {
  473. // On Windows set the badge on the first window found.
  474. UpdateBadgeContents(window->GetAcceleratedWidget(), badge_content,
  475. badge_alt_string);
  476. }
  477. return true;
  478. }
  479. void Browser::UpdateBadgeContents(
  480. HWND hwnd,
  481. const absl::optional<std::string>& badge_content,
  482. const std::string& badge_alt_string) {
  483. SkBitmap badge;
  484. if (badge_content) {
  485. std::string content = badge_content.value();
  486. constexpr int kOverlayIconSize = 16;
  487. // This is the color used by the Windows 10 Badge API, for platform
  488. // consistency.
  489. constexpr int kBackgroundColor = SkColorSetRGB(0x26, 0x25, 0x2D);
  490. constexpr int kForegroundColor = SK_ColorWHITE;
  491. constexpr int kRadius = kOverlayIconSize / 2;
  492. // The minimum gap to have between our content and the edge of the badge.
  493. constexpr int kMinMargin = 3;
  494. // The amount of space we have to render the icon.
  495. constexpr int kMaxBounds = kOverlayIconSize - 2 * kMinMargin;
  496. constexpr int kMaxTextSize = 24; // Max size for our text.
  497. constexpr int kMinTextSize = 7; // Min size for our text.
  498. badge.allocN32Pixels(kOverlayIconSize, kOverlayIconSize);
  499. SkCanvas canvas(badge, skia::LegacyDisplayGlobals::GetSkSurfaceProps());
  500. SkPaint paint;
  501. paint.setAntiAlias(true);
  502. paint.setColor(kBackgroundColor);
  503. canvas.clear(SK_ColorTRANSPARENT);
  504. canvas.drawCircle(kRadius, kRadius, kRadius, paint);
  505. paint.reset();
  506. paint.setColor(kForegroundColor);
  507. SkFont font;
  508. SkRect bounds;
  509. int text_size = kMaxTextSize;
  510. // Find the largest |text_size| larger than |kMinTextSize| in which
  511. // |content| fits into our 16x16px icon, with margins.
  512. do {
  513. font.setSize(text_size--);
  514. font.measureText(content.c_str(), content.size(), SkTextEncoding::kUTF8,
  515. &bounds);
  516. } while (text_size >= kMinTextSize &&
  517. (bounds.width() > kMaxBounds || bounds.height() > kMaxBounds));
  518. canvas.drawSimpleText(
  519. content.c_str(), content.size(), SkTextEncoding::kUTF8,
  520. kRadius - bounds.width() / 2 - bounds.x(),
  521. kRadius - bounds.height() / 2 - bounds.y(), font, paint);
  522. }
  523. taskbar_host_.SetOverlayIcon(hwnd, badge, badge_alt_string);
  524. }
  525. void Browser::SetLoginItemSettings(LoginItemSettings settings) {
  526. std::wstring key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  527. base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_ALL_ACCESS);
  528. std::wstring startup_approved_key_path =
  529. L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved"
  530. L"\\Run";
  531. base::win::RegKey startup_approved_key(
  532. HKEY_CURRENT_USER, startup_approved_key_path.c_str(), KEY_ALL_ACCESS);
  533. PCWSTR key_name =
  534. !settings.name.empty() ? settings.name.c_str() : GetAppUserModelID();
  535. if (settings.open_at_login) {
  536. std::wstring exe = base::UTF16ToWide(settings.path);
  537. if (FormatCommandLineString(&exe, settings.args)) {
  538. key.WriteValue(key_name, exe.c_str());
  539. if (settings.enabled) {
  540. startup_approved_key.DeleteValue(key_name);
  541. } else {
  542. HKEY hard_key;
  543. LPCTSTR path = TEXT(
  544. "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp"
  545. "roved\\Run");
  546. LONG res =
  547. RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hard_key);
  548. if (res == ERROR_SUCCESS) {
  549. UCHAR disable_startup_binary[] = {0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
  550. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  551. RegSetValueEx(hard_key, key_name, 0, REG_BINARY,
  552. reinterpret_cast<const BYTE*>(disable_startup_binary),
  553. sizeof(disable_startup_binary));
  554. }
  555. }
  556. }
  557. } else {
  558. // if open at login is false, delete both values
  559. startup_approved_key.DeleteValue(key_name);
  560. key.DeleteValue(key_name);
  561. }
  562. }
  563. Browser::LoginItemSettings Browser::GetLoginItemSettings(
  564. const LoginItemSettings& options) {
  565. LoginItemSettings settings;
  566. std::wstring keyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  567. base::win::RegKey key(HKEY_CURRENT_USER, keyPath.c_str(), KEY_ALL_ACCESS);
  568. std::wstring keyVal;
  569. // keep old openAtLogin behaviour
  570. if (!FAILED(key.ReadValue(GetAppUserModelID(), &keyVal))) {
  571. std::wstring exe = base::UTF16ToWide(options.path);
  572. if (FormatCommandLineString(&exe, options.args)) {
  573. settings.open_at_login = keyVal == exe;
  574. }
  575. }
  576. // iterate over current user and machine registries and populate launch items
  577. // if there exists a launch entry with property enabled=='true',
  578. // set executable_will_launch_at_login to 'true'.
  579. boolean executable_will_launch_at_login = false;
  580. std::vector<Browser::LaunchItem> launch_items;
  581. base::win::RegistryValueIterator hkcu_iterator(HKEY_CURRENT_USER,
  582. keyPath.c_str());
  583. base::win::RegistryValueIterator hklm_iterator(HKEY_LOCAL_MACHINE,
  584. keyPath.c_str());
  585. launch_items = GetLoginItemSettingsHelper(
  586. &hkcu_iterator, &executable_will_launch_at_login, L"user", options);
  587. std::vector<Browser::LaunchItem> launch_items_hklm =
  588. GetLoginItemSettingsHelper(&hklm_iterator,
  589. &executable_will_launch_at_login, L"machine",
  590. options);
  591. launch_items.insert(launch_items.end(), launch_items_hklm.begin(),
  592. launch_items_hklm.end());
  593. settings.executable_will_launch_at_login = executable_will_launch_at_login;
  594. settings.launch_items = launch_items;
  595. return settings;
  596. }
  597. PCWSTR Browser::GetAppUserModelID() {
  598. return GetRawAppUserModelID();
  599. }
  600. std::string Browser::GetExecutableFileVersion() const {
  601. base::FilePath path;
  602. if (base::PathService::Get(base::FILE_EXE, &path)) {
  603. ScopedAllowBlockingForElectron allow_blocking;
  604. std::unique_ptr<FileVersionInfo> version_info = FetchFileVersionInfo();
  605. return base::UTF16ToUTF8(version_info->product_version());
  606. }
  607. return ELECTRON_VERSION_STRING;
  608. }
  609. std::string Browser::GetExecutableFileProductName() const {
  610. return GetApplicationName();
  611. }
  612. bool Browser::IsEmojiPanelSupported() {
  613. // emoji picker is supported on Windows 10's Spring 2018 update & above.
  614. return base::win::GetVersion() >= base::win::Version::WIN10_RS4;
  615. }
  616. void Browser::ShowEmojiPanel() {
  617. // This sends Windows Key + '.' (both keydown and keyup events).
  618. // "SendInput" is used because Windows needs to receive these events and
  619. // open the Emoji picker.
  620. INPUT input[4] = {};
  621. input[0].type = INPUT_KEYBOARD;
  622. input[0].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND);
  623. input[1].type = INPUT_KEYBOARD;
  624. input[1].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD);
  625. input[2].type = INPUT_KEYBOARD;
  626. input[2].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND);
  627. input[2].ki.dwFlags |= KEYEVENTF_KEYUP;
  628. input[3].type = INPUT_KEYBOARD;
  629. input[3].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD);
  630. input[3].ki.dwFlags |= KEYEVENTF_KEYUP;
  631. ::SendInput(4, input, sizeof(INPUT));
  632. }
  633. void Browser::ShowAboutPanel() {
  634. base::Value::Dict dict;
  635. std::string aboutMessage = "";
  636. gfx::ImageSkia image;
  637. // grab defaults from Windows .EXE file
  638. std::unique_ptr<FileVersionInfo> exe_info = FetchFileVersionInfo();
  639. dict.Set("applicationName", exe_info->file_description());
  640. dict.Set("applicationVersion", exe_info->product_version());
  641. // Merge user-provided options, overwriting any of the above
  642. dict.Merge(about_panel_options_.Clone());
  643. std::vector<std::string> stringOptions = {
  644. "applicationName", "applicationVersion", "copyright", "credits"};
  645. const std::string* str;
  646. for (std::string opt : stringOptions) {
  647. if ((str = dict.FindString(opt))) {
  648. aboutMessage.append(*str).append("\r\n");
  649. }
  650. }
  651. if ((str = dict.FindString("iconPath"))) {
  652. base::FilePath path = base::FilePath::FromUTF8Unsafe(*str);
  653. electron::util::PopulateImageSkiaRepsFromPath(&image, path);
  654. }
  655. electron::MessageBoxSettings settings = {};
  656. settings.message = aboutMessage;
  657. settings.icon = image;
  658. settings.type = electron::MessageBoxType::kInformation;
  659. electron::ShowMessageBox(settings,
  660. base::BindOnce([](int, bool) { /* do nothing. */ }));
  661. }
  662. void Browser::SetAboutPanelOptions(base::Value::Dict options) {
  663. about_panel_options_ = std::move(options);
  664. }
  665. } // namespace electron